语句中Python中的多个variables

是否有可能在Python中使用with语句声明多个variables?

就像是:

 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) 

…或者是同时清理两个资源的问题?

从v3.1和Python 2.7 开始 , Python 3是可能的。 新with语法支持多个上下文pipe理器:

 with A() as a, B() as b, C() as c: doSomething(a,b,c) 

__exit__()不同的是,即使C()或它的__enter__()方法引发exception,这也保证了ab__exit__()

contextlib.nested支持这个:

 import contextlib with contextlib.nested(open("out.txt","wt"), open("in.txt")) as (file_out, file_in): ... 

更新:
引用关于contextlib.nested的文档:

从2.7版开始弃用 :with-statement现在直接支持这个function(没有混淆错误的怪癖)。

有关更多信息,请参阅RafałDowgird的答案 。

我想你想这样做:

 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)