Module 13 · File Handling — topic 8 of 15
with statements
Context managers and the with statement: automatic file closing, opening several files at once, how __enter__ and __exit__ work, and writing your own context managers with contextlib.
Learning objectives
- Use with to manage files
- Open several files in one with statement
- Write simple context managers
Definition
A with statement runs a block inside a context manager. The manager's setup code runs on entry, and its cleanup code runs on exit — always, whether the block finishes normally or raises an exception. File objects are context managers that close themselves.
Introduction
with open(...) as f: is the standard way to work with files in Python. It is shorter than try/finally and impossible to get wrong.
Why it matters
Context managers package setup and cleanup together, so resources such as files, locks and connections can't be leaked.
Detailed explanation
with EXPRESSION as name: evaluates the expression to get a context manager, calls its __enter__ method, and binds the result to name.
When the block ends — normally, by return/break, or by exception — the manager's __exit__ method runs. For files, __exit__ closes the file.
__exit__ receives the exception type, value and traceback (or three Nones). Returning a true value suppresses the exception; returning False lets it propagate.
Several managers can be combined: with open(a) as src, open(b, "w") as dst: ... Parentheses allow spreading them over several lines.
contextlib.contextmanager turns a generator function into a context manager: code before yield is setup, code after (in finally) is cleanup.
Many standard objects are context managers: locks, database connections, zipfile.ZipFile, tempfile.TemporaryDirectory and decimal.localcontext.
The variable bound by as still exists after the block, but the file it refers to is closed.
Syntax
- Setup on entry, cleanup on exit.
- Files close automatically.
- Combine several managers in one with.
Code examples
Automatic closing
True
Two files at once
1: ONE 2: TWO 3: THREE
More examples
Writing context managers
enter load working exit load (error: None) enter parse exit parse (error: ValueError) error still propagated opened ctx.txt closed ctx.txt
Step-by-step explanation
- Section's __exit__ runs in both cases and sees the ValueError in the second.
- Returning False means the exception continues to the outer try.
- The generator-based opened does the same with less code: setup before yield, cleanup in finally.
Expected output
Running “Writing context managers” prints exactly:
Practical applications
- with lock: in multithreaded code.
- with sqlite3.connect(...) as conn: for transactions.
Best practices
- Use with for every file you open.
- Keep the with block focused on using the resource.
- Use contextlib for simple custom managers.
Common mistakes
Using the file after the block
Avoid
Prefer
The file is closed when the block ends.
Important notes
- contextlib.ExitStack manages a variable number of context managers.
Key takeaways
- with guarantees cleanup via __exit__.
- Files close automatically at the end of the block.
- contextmanager makes writing managers easy.
Try it yourself
- 1Write a context manager that prints how many lines were written to a file during the block.
- 2Merge two text files into a third using a single with statement.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?