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?