Python Forum

Full Version: a conditional with
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
User a ternary expression: with open_file if already_open else maybe_open(...) as wf:.