0

Is it possible to use the with context manager syntax with more than one object in Python?

For example, something like:

with open("file1.txt") as file1, open("file2.txt") as file2:
    file1.write("this is file 1")
    file2.write("this is file 2")

A duckduckgo and internal search of this site indicates the answer is probably "no". Given that the likely answer is "no", what is the next best option? (Of course, if the answer is "yes", please let me know how.)

Perhaps a set of nexted context managers, such as the following, would be a good solution?

with open("file1.txt") as file1:
    with open("file2.txt") as file2:
        file1.write("this is file 1")
        file2.write("this is file 2")

Is there any reason why one would not want to do this? Is the order likely to matter?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

1 Answers1

1

This

with open("file1.txt") as file1, open("file2.txt") as file2:
    file1.write("this is file 1")
    file2.write("this is file 2")

is compliant with with statement definition given by docs

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

where * denotes 0 or more repetitions

Daweo
  • 31,313
  • 3
  • 12
  • 25