【发布时间】:2019-05-07 16:26:00
【问题描述】:
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
我不想重复“做事”,因为它们之间是一样的。但是如何使用条件来控制 with 上下文?
【问题讨论】:
标签: python python-2.7 conditional-statements with-statement