Skip to content

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.

Beginner 10 min read·Lesson 201 of 306 in Python Programming

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

Python
with open("in.txt", encoding="utf-8") as src, \
open("out.txt", "w", encoding="utf-8") as dst:
for line in src:
dst.write(line.upper())
  • Setup on entry, cleanup on exit.
  • Files close automatically.
  • Combine several managers in one with.

Code examples

Automatic closing

Python
with open("w.txt", "w", encoding="utf-8") as f:
f.write("hello")
print(f.closed)
Output
True

Two files at once

Python
with open("in.txt", "w", encoding="utf-8") as f:
f.write("one\ntwo\nthree\n")
with open("in.txt", encoding="utf-8") as src, open("out.txt", "w", encoding="utf-8") as dst:
for n, line in enumerate(src, 1):
dst.write(f"{n}: {line.upper()}")
with open("out.txt", encoding="utf-8") as f:
print(f.read(), end="")
Output
1: ONE
2: TWO
3: THREE

More examples

Writing context managers

Python
from contextlib import contextmanager
class Section:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"enter {self.name}")
return self
def __exit__(self, exc_type, exc, tb):
print(f"exit {self.name} (error: {exc_type.__name__ if exc_type else None})")
return False
with Section("load"):
print(" working")
try:
with Section("parse"):
int("x")
except ValueError:
print("error still propagated")
@contextmanager
def opened(path):
f = open(path, "w", encoding="utf-8")
print("opened", path)
try:
yield f
finally:
f.close()
print("closed", path)
with opened("ctx.txt") as f:
f.write("hi")
Output
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:

TextOutput
enter load
working
exit load (error: None)
enter parse
exit parse (error: ValueError)
error still propagated
opened ctx.txt
closed ctx.txt

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

with open(p, encoding="utf-8") as f:
pass
data = f.read()

Prefer

with open(p, encoding="utf-8") as f:
data = f.read()

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

  1. 1
    Write a context manager that prints how many lines were written to a file during the block.
  2. 2
    Merge 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?
Practise this topic