0 votes
1 view
in Python by (47.8k 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:

file_out.write(line)

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

1 Answer

0 votes
by (107k 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:

doSomething(a,b,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:-

contextlib.nested():-

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):

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...