Python控件“with”上下文管理器和条件
Python2.7可以使用条件来控制上下文管理器中的上下文吗?我的场景是,如果gzip文件存在,我想附加到它,如果它不存在,我想写入一个新文件。伪代码是:Python控件“with”上下文管理器和条件,python,python-2.7,conditional-statements,with-statement,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: 或者 我不想重复做的事情,因为他们之间是一样的。但是如何使用条件来控制上下文呢?您可以尝试为do编写一个函数 def do_stuff(): #
with gzip.open(outfile, 'a+') if os.isfile(outfile) else with open(outfile, 'w') as outhandle:
或者
我不想重复做的事情,因为他们之间是一样的。但是如何使用条件来控制上下文呢?您可以尝试为do编写一个函数
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
这一点很好,我在其他地方也做过。但我想知道在with语句中是否有这样做的方法。
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