Rusty Lemur
Rusty Lemur

Reputation: 1875

Python control "with" context manager with conditional

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

Answers (2)

aydow
aydow

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

Zander
Zander

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

Related Questions