Is it possible to declare more than one variable using a with statement in Python?
Something like:
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)
… or is cleaning up two resources at the same time the problem?
It is possible in Python 3 since v3.1 and Python 2.7. The new
withsyntax supports multiple context managers:Unlike the
contextlib.nested, this guarantees thataandbwill have their__exit__()‘s called even ifC()or it’s__enter__()method raises an exception.You can also use earlier variables in later definitions (h/t Ahmad below):
As of Python 3.10, you can use parentheses: