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?

4
  • The answer is yes, you can open multiple files in same line Commented Jul 27, 2021 at 14:31
  • Have you tried your first code sample? That is the way to do it Commented Jul 27, 2021 at 14:34
  • When with statements were added in Python 2.5, they were limited to a single context expression. Support for multiple context expressions was added in Python 3.1. Commented Jul 27, 2021 at 14:37
  • docs.python.org/3/reference/… Commented Jul 27, 2021 at 14:39

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice to know my guess was correct, wasn't able to find an example of this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.