Python Forum
a conditional with - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: a conditional with (/thread-21148.html)



a conditional with - Skaperen - Sep-16-2019

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?


RE: a conditional with - ichabod801 - Sep-17-2019

User a ternary expression: with open_file if already_open else maybe_open(...) as wf:.