Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a conditional with
#1
i have a case where i'd like to use a with statement opening a file for a body of several statements of code. the catch is that in some cases i do not want to do the open and have an already open file i want to use, instead. it might be like this:
    with maybeopen(condition,filename,'w') as wf:
        print('line 1',file=wf)
        print('line 2',file=wf)
        print('line 3',file=wf)
        print('line 4',file=wf)
        print('line 5',file=wf)
    ...
where maybeopen() would open the file if condition is true and not open it if not true in which case wf will already reference an open writeable file (maybe set as sys.stdout, but don't assume so). how can i do a with like this or is this a case to use the old way of maybe open and maybe close? if i code maybeopen() to return the already open file if the condition fails, how can i be sure the file being opened get closed and the file that is already open does not get closed?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
User a ternary expression: with open_file if already_open else maybe_open(...) as wf:.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020