Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

Is it possible to declare more than one variable using a with the 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:


... or is cleaning up two resources at the same time the problem?

1 Answer

0 votes
by (106k points)

Yes, we can declare the multiple variables using with the statement in Python but for that, you should have to use Python 3. In Python 3 the new with syntax supports multiple context managers. Below is the syntax that explains how we can declare the multiple variables in Python.

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


You have another way that you can use to declare the multiple arguments using with the statement in Python.  For that, you can use the contextlib.nested. Below is the code that explains the use of contextlib.nested() function:-


This function combines the multiple context managers into a single nested context manager. It has been deprecated in favour of the multiple manager form of the with the statement.

import contextlib

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

Browse Categories