Python control "with" 有条件的上下文管理器
Python control "with" context manager with conditional
Python2.7 可以使用条件来控制 "with" 上下文管理器吗?我的场景是,如果存在一个 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
我不想重复 "do stuff" 因为它们之间是一样的。但是如何使用条件来控制 with 上下文?
您可以尝试只为 "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()
记住函数也可以赋值给变量
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
Python2.7 可以使用条件来控制 "with" 上下文管理器吗?我的场景是,如果存在一个 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
我不想重复 "do stuff" 因为它们之间是一样的。但是如何使用条件来控制 with 上下文?
您可以尝试只为 "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()
记住函数也可以赋值给变量
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