How to Use Several Context Managers in One with Statement in Python
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
with (
<manager1> as <name1>,
<manager2> as <name2>,
):
...
| Part | What 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:
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())

Step 2: Run It
uv run python two_files.py
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
| Mistake | What happens | Do this instead |
|---|---|---|
Nesting a with inside another for two items | It 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 older | They came with Python 3.10 | Use Python 3.10 or newer |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
ValueError: I/O operation on closed file. | A file was used after its with block closed it | Do 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
- The with statement — several items, and the parentheses.
