How to Use the with Statement in Python
Files, network connections and locks have to be closed or released when you're done with them, even when something goes wrong halfway. Python's with statement does that for you: whatever you open in the with line is cleaned up as soon as the indented block ends. This guide shows it with a file on Python 3.15.2.
Syntax
with <expression> as <name>:
<use name>
# here, after the block, <name> is closed or released
| Part | What it means |
|---|---|
<expression> | Something that supports with, such as open(...) or urllib.request.urlopen(...) |
as <name> | The name you use for it inside the block |
| The indented block | Runs with the resource open. When it ends, for any reason, the resource is cleaned up |
Python's language reference says: "The with statement is used to wrap the execution of a block with methods defined by a context manager". For a file, that clean-up method closes it.
The Example
The script writes a note to a file inside a with block and checks the file's closed flag inside the block and after it.
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
with open("note.txt", "w", encoding="utf-8") as file:
file.write("Remember the milk")
print("Inside the block, closed:", file.closed)
print("After the block, closed:", file.closed)

Step 2: Run It
uv run python with_demo.py
Inside the block, closed: False
After the block, closed: True

The file was open inside the block and closed right after it, without a close() call. note.txt now holds the text. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using the file after the block: file.write(...) below it | ValueError: I/O operation on closed file. | Keep every use inside the indented block |
Opening without with and forgetting close() | The tutorial warns this "might result in the arguments of f.write() not being completely written to the disk" | Use with |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
ValueError: I/O operation on closed file. | The code runs after the with block ended | Indent it into the block |
FAQ
Does with close the file when an error happens inside the block?
Yes. That's its main job: the clean-up runs however the block ends, including when an exception leaves it.
Can I open two things in one with?
Yes, separated by commas: with open("a.txt") as a, open("b.txt") as b:.
Conclusion
The file was open inside the with block (closed: False) and closed right after it (closed: True), and using it afterwards raised ValueError. Use with for anything that needs closing.
Additional Resources
- The with statement — the language reference.
- Reading and Writing Files — the tutorial's
with open(...)examples.
