Skip to main content

How to Use the with Statement in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
with <expression> as <name>:
<use name>
# here, after the block, <name> is closed or released
PartWhat 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 blockRuns 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_demo.py
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)

The with_demo.py script in a macOS-style code window: it opens note.txt for writing in a with block, writes Remember the milk, prints file.closed inside the block, and prints it again after the block.

Step 2: Run It​

Terminal
uv run python with_demo.py
Output
Inside the block, closed: False
After the block, closed: True

The terminal after uv run python with_demo.py: Inside the block, closed: False, then 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​

MistakeWhat happensDo this instead
Using the file after the block: file.write(...) below itValueError: 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​

SymptomLikely causeFix
ValueError: I/O operation on closed file.The code runs after the with block endedIndent 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​