在Python3中,我们可以在with语句中使用多个上下文。但是,如果不能立即在with语句中构造它们,是否可以输入多个上下文?可以这样做吗?
def files():
return open('a.txt', 'w'), open('b.txt', 'w')
with files():
pass
或者这个:
files = open('a.txt', 'w'), open('b.txt', 'w')
with files:
pass
答案 0 :(得分:2)
from contextlib import contextmanager
@contextmanager
def files():
with open('a.txt', 'w') as f1, open('b.txt', 'w') as f2:
yield f1,f2
也许吗?
with files() as (f1,f2):
print(f1,f2)
答案 1 :(得分:2)
使用contextlib.ExitStack
的示例:
from contextlib import ExitStack
def files(stack, *args):
return [stack.enter_context(open(f, "w")) for f in args]
with ExitStack() as stack:
f1, f2 = files(stack, "a.txt", "b.txt")
...
或没有包装器
with ExitStack() as stack:
f1, f2 = [stack.enter_context(open(f, "w")) for f in ["a.txt", "b.txt"]]
...
但是,当您提前知道要打开多少文件(并且文件数量很少)时,with
语句的多管理器形式(如Joran Beasley's answer所示就更简单了)