PY-101 ยท Files and errors
with and context managers
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A with statement runs a block of code inside a context manager, which sets something up at the start and always cleans it up at the end, even if an error happens. with open(...) as f: closes the file for you. The same pattern is used for database connections, locks and timers.
- Use with for files
- Know why cleanup matters
- Write a tiny context manager
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
from contextlib import contextmanagerwith open("log.txt", "w") as f:f.write("started\n")print("Inside, closed?", f.closed)print("After, closed?", f.closed)@contextmanagerdef step(name):print("Start", name)yieldprint("Done", name)with step("backup"):print("Copying files...")
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
Inside, closed? False
After, closed? True
Start backup
Copying files...
Done backup ๐ฏ Write a context manager tag(name) with @contextmanager that prints <name> before the block and </name> after it. Use it so the output is <b>, Hello, </b> on three lines.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
def tag(name): print(f"<{name}>"); yield; print(f"</{name}>"), then with tag("b"): print("Hello")
- The problemA script opens 500 files and forgets to close them. Around file 250 the computer refuses to open any more. with makes "forgot to close" impossible.
- The Python idea
with something() as name:A with statement runs a block of code inside a context manager, which sets something up at the start and always cleans it up at the end, even if an error happens. - In real lifeDatabase libraries use with to make sure a transaction is committed when all goes well and rolled back when something fails.
Start with a question
A script opens 500 files and forgets to close them. Around file 250 the computer refuses to open any more. with makes "forgot to close" impossible.
Leaked files, connections and locks are classic production bugs. with prevents them by design.
Explain it like I'm 10
with is like a library that checks books back in for you the moment you leave the reading room, even if you rush out.
The technical explanation
When the with block ends (normally or by an exception) the context manager's cleanup runs.
f.closed is False inside the block and True afterwards.
With contextlib.contextmanager, code before yield is the setup and code after it is the cleanup.
Syntax
with something() as name:
... Real-world scenario
Database libraries use with to make sure a transaction is committed when all goes well and rolled back when something fails.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: CSV and JSON โQuestions people ask
Why use with open instead of open and close?
with closes the file even if an error happens halfway, and it is shorter. Forgetting close() leaks files.
Can I open two files in one with statement?
Yes: with open("in.txt") as src, open("out.txt", "w") as dst:.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner Why use with open instead of open and close?
with closes the file even if an error happens halfway, and it is shorter. Forgetting close() leaks files.
beginner Can I open two files in one with statement?
Yes: with open("in.txt") as src, open("out.txt", "w") as dst:.
intermediate What does with open(...) do at the end of the block?
Closes the file. The file is closed automatically.
intermediate Does cleanup still run if an error happens inside with?
Yes. That is the whole point.
Quick revision
Remember
- Use with for files
- Know why cleanup matters
- Write a tiny context manager
- You do not need f.close() inside a with block. It happens automatically when the block ends.
Syntax
with something() as name:
... Official documentation
- The with statement (docs.python.org)
- contextlib (docs.python.org)