In short
Opened files, network connections and locks must always be closed, even when your code crashes halfway. The with statement guarantees that cleanup, so you never leak resources again.
The with statement sets something up and guarantees it is cleaned up afterwards, even if an error happens. with open(...) as f: closes the file automatically, and the same pattern is used for locks and database connections.

Think of it like this
A hotel room that checks you out automatically
Imagine a hotel that hands you the key at the door and, however you leave (calmly, in a rush, or because the fire alarm rang), takes the key back and locks the room behind you. with is that hotel: setup on the way in, guaranteed cleanup on the way out.
Watch it happen
What with open(...) as f actually does
1/4Python calls __enter__, which opens the file and hands it to you as f.
The big ideas
What you need to know
Cleanup is guaranteed
Whether the block finishes, returns early or raises, __exit__ always runs.
Several at once
with open('a.txt') as src, open('b.txt', 'w') as dst: manages two files in one line.
Not just files
Locks, database connections, temporary directories and timers all use the same pattern.
Write your own
Decorate a generator with @contextmanager from contextlib: code before yield is setup, code after is cleanup.
See it in code
Walk through the code
1import time2from contextlib import contextmanager3 4with open("marks.txt", "w", encoding="utf-8") as f:5 f.write("Riya,88\n")6print(f.closed) # True, closed for us7 8@contextmanager9def timer(label):10 start = time.perf_counter()11 try:12 yield13 finally:14 elapsed = time.perf_counter() - start15 print(f"{label} took {elapsed:.3f}s")16 17with timer("Summing"):18 total = sum(range(10_000_000))19 20with open("marks.txt", encoding="utf-8") as src, \21 open("copy.txt", "w", encoding="utf-8") as dst:22 dst.write(src.read())1/5After the block ends, f.closed is True. You never call f.close() yourself.
Automatic file closing, a home-made timing context manager, and two files managed together.
Save yourself the pain
Common mistakes
Oops
f = open('data.txt') and forgetting f.close(), or crashing before it runs.
Do this instead
Use with open('data.txt', encoding='utf-8') as f: so closing is automatic.
Oops
Using the file after the with block ends.
Do this instead
The file is closed once the indentation ends. Read what you need into a variable inside the block.
Your mission
Build a context manager
Quick check
If an exception happens inside with open(...) as f:, what happens to the file?
Go deeper
- 1Rewrite any open()/close() pair you have as a with block.
- 2Open two files in one with statement to copy from one to the other.
- 3Raise an error inside a with block and confirm the file still gets closed.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.