Reputation: 1875
Can Python2.7 use a conditional to control a "with" context manager? My scenario is that if a gzipped file exists, I want to append to it, and if it does not exist, I want to write to a new file. The pseudo code is:
with gzip.open(outfile, 'a+') if os.isfile(outfile) else with open(outfile, 'w') as outhandle:
Or...
if os.isfile(outfile):
with gzip.open(outfile, 'a+') as outhandle:
# do stuff
else:
with open(outfile, 'w') as outhandle:
# do the same stuff
I don't want to repeat the "do stuff" since it will be the same between them. But how can I use a conditional to control the with context?
Upvotes: 0
Views: 137
Reputation: 3801
Remember that functions can also be assigned to variables
if os.isfile(outfile):
open_function = gzip.open
mode = 'a+'
else:
open_function = open
mode = 'w'
with open_function(outfile, mode) as outhandle:
# do stuff
Upvotes: 1
Reputation: 65
You could try just writing a function for the "do stuff"
def do_stuff():
#do stuff here
if os.isfile(outfile):
with gzip.open(outfile, 'a+') as outhandle:
do_stuff()
else:
with open(outfile, 'w') as outhandle:
do_stuff()
Upvotes: 1