Skip to main content

How to Use Several Context Managers in One with Statement in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Copying from one file into another needs both open at the same time. You could nest one with inside another, but one with statement can manage several things at once, and closes them all when the block ends. This guide copies a file that way, with real output from Python 3.15.2.

Syntax​

Syntax
with (
<manager1> as <name1>,
<manager2> as <name2>,
):
...
PartWhat it means
<manager1> as <name1>The first thing to open, such as open("source.txt"), and its name in the block
,Separates the items; a comma after the last one is allowed
( ... )Lets the items span several lines

Python's language reference: "With more than one item, the context managers are processed as if multiple with statements were nested." The parentheses came with Python 3.10: "Changed in version 3.10: Support for using grouping parentheses to break the statement in multiple lines."

Prerequisites​

  • uv and Python 3.10 or newer. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

source.txt holds one line, hello from source.txt:

two_files.py
with (
open("source.txt") as source,
open("copy.txt", "w") as copy,
):
copy.write(source.read())

with open("copy.txt") as copy:
print(copy.read())

The two_files.py script in a macOS-style code window: one with statement opens source.txt and copy.txt in parentheses and writes the first into the second, then copy.txt is read back.

Step 2: Run It​

Terminal
uv run python two_files.py
Output
hello from source.txt

The script's output in a terminal: hello from source.txt.

Both files were open inside the block, and copy.txt now holds the line. When the block ended, both were closed.

Common Mistakes​

MistakeWhat happensDo this instead
Nesting a with inside another for two itemsIt works, but Ruff's SIM117 rule reports "Use a single with statement with multiple contexts instead of nested with statements"Combine them in one with
Relying on the parentheses in Python 3.9 or olderThey came with Python 3.10Use Python 3.10 or newer

Troubleshooting​

SymptomLikely causeFix
ValueError: I/O operation on closed file.A file was used after its with block closed itDo the work inside the block

FAQ​

In which order are the items opened and closed?​

As if nested: opened from the first to the last, and closed in reverse, the last one first.

Can I mix different kinds of context managers?​

Yes. Any objects that work in a with can share one, such as a file and a database connection wrapped in contextlib.closing.

Conclusion​

One with statement opened source.txt and copy.txt together, the copy received hello from source.txt, and both closed when the block ended.

Additional Resources​