0

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?

aydow
  • 3,673
  • 2
  • 23
  • 40
Rusty Lemur
  • 1,697
  • 1
  • 21
  • 54
  • Does this answer your question? [Pythonic way to use context manager conditionally](https://stackoverflow.com/questions/33928590/pythonic-way-to-use-context-manager-conditionally) – ideasman42 Oct 14 '21 at 00:21

2 Answers2

1

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()
Zander
  • 65
  • 1
  • 9
  • Good point, and I have done that in other places. But I'm wondering if there is a way to do it in the with statement. – Rusty Lemur May 07 '19 at 16:44
1

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
aydow
  • 3,673
  • 2
  • 23
  • 40