带有条件的Python控件“带有”上下文管理器

时间:2019-05-07 16:26:00

标签: python python-2.7 conditional-statements with-statement

Python2.7是否可以使用条件控件来控制“具有”上下文管理器?我的情况是,如果存在gzip压缩文件,我想追加到该文件,如果不存在,我想写入一个新文件。伪代码为:

with gzip.open(outfile, 'a+') if os.isfile(outfile) else with open(outfile, 'w') as outhandle:

或者...

if os.isfile(outfile):
    with gzip.open(outfile, 'a+') as outhandle:
        # do stuff
else:
    with open(outfile, 'w') as outhandle:
        # do the same stuff

我不想重复“做某事”,因为它们之间是相同的。但是,如何使用条件来控制with上下文呢?

2 个答案:

答案 0 :(得分:1)

您可以尝试只为“做事”编写函数

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()

答案 1 :(得分:0)

请记住,也可以将函数分配给变量

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