是否可以在Python语言中使用with
语句声明多个变量?
类似于:
from __future__ import with_statement
with open("out.txt","wt"), open("in.txt") as file_out, file_in:
for line in file_in:
file_out.write(line)
..。或者同时清理两个资源就是问题所在?
发布于 2009-07-02 11:25:51
这在Python 3 since v3.1和Python 2.7中是可能的。新的with
syntax支持多个上下文管理器:
with A() as a, B() as b, C() as c:
doSomething(a,b,c)
与contextlib.nested
不同的是,这保证了a
和b
将调用它们的__exit__()
,即使C()
或它的__enter__()
方法引发异常。
您还可以在以后的定义中使用较早的变量(下面的h/t Ahmad ):
with A() as a, B(a) as b, C(a, b) as c:
doSomething(a, c)
从Python3.10开始,you can use parentheses
with (
A() as a,
B(a) as b,
C(a, b) as c,
):
doSomething(a, c)
发布于 2009-05-21 14:55:23
我认为你应该这样做:
from __future__ import with_statement
with open("out.txt","wt") as file_out:
with open("in.txt") as file_in:
for line in file_in:
file_out.write(line)
发布于 2021-02-26 23:37:46
从Python3.10开始,Parenthesized context managers有了一个新特性,它支持如下语法:
with (
A() as a,
B() as b
):
do_something(a, b)
https://stackoverflow.com/questions/893333
复制相似问题