ZetCode

Python with statement

last modified November 29, 2026 Python 3.15

In this article we show how to use the with statement in Python.

Many objects hold a resource that must be released after use: an open file, a lock, a database transaction, a temporary directory. The with statement runs a block of code and guarantees that the release happens when the block ends, whether it ends normally, by an exception, or by a return or break statement.

An object that can be used in a with statement is called a context manager. This article shows how to use existing context managers. Writing your own, with a class or with the contextlib module, is covered in Python context managers.

Opening a file

The most common context manager is a file object returned by open. The file is closed automatically at the end of the with block.

first_with.py
with open("notes.txt", "w") as f:
    f.write("buy coffee\n")
    f.write("call Martin\n")

with open("notes.txt") as f:
    print(f.read(), end="")

print("closed:", f.closed)

The first statement opens notes.txt for writing and binds the file object to f. When the indented block ends, the file is closed and the written data is flushed to disk. The second statement opens the file for reading. After the block, the closed attribute confirms that the file was closed without an explicit close call.

$ python first_with.py
buy coffee
call Martin
closed: True

The name after the block

The with statement does not create a new scope. The variable bound by as exists after the block, but the object it refers to has been closed.

closed_after.py
with open("notes.txt") as f:
    first = f.readline()

print(first, end="")
print("closed:", f.closed)
print(f.name)
print(f.readline())

first holds the line read inside the block and can be used afterwards. The file object also still exists, and its attributes such as name can be read. Reading from it, however, raises a ValueError, because the file is closed. Data that is needed later should be read inside the block.

$ python closed_after.py
buy coffee
closed: True
notes.txt
Traceback (most recent call last):
  File "/home/user/with-keyword/closed_after.py", line 7, in <module>
    print(f.readline())
          ~~~~~~~~~~^^
ValueError: I/O operation on closed file.

Closing after an error

The cleanup also happens when an exception leaves the block. The with statement does not handle the exception; it closes the file and lets the exception propagate.

on_error.py
try:
    with open("numbers.txt", "w") as f:
        f.write("1 2 3\n")
        print("inside, closed:", f.closed)
        total = 10 / 0
        f.write("never written\n")
except ZeroDivisionError as e:
    print("error:", e)
    print("after error, closed:", f.closed)

with open("numbers.txt") as f:
    print(f.read(), end="")

The division by zero raises an exception in the middle of the block. The second write call is skipped, but the file is closed before the exception reaches the except clause. The data written before the error is saved. Exceptions are covered in Python exceptions.

$ python on_error.py
inside, closed: False
error: division by zero
after error, closed: True
1 2 3

The equivalent try/finally

Before the with statement existed, cleanup was written with try and finally. The finally clause runs in all cases, so it is the right place for close.

try_finally.py
f = open("log.txt", "w")
try:
    f.write("started\n")
    f.write("finished\n")
finally:
    f.close()

print("closed:", f.closed)

with open("log.txt") as f:
    lines = f.readlines()

print(lines)

The first part does by hand what with does automatically. The with version is shorter and cannot forget the cleanup. In general, a with statement calls the manager's __enter__ method at the start of the block and its __exit__ method at the end, in a way similar to this try/finally construct. Unlike finally, __exit__ is told whether an exception occurred.

$ python try_finally.py
closed: True
['started\n', 'finished\n']

Leaving the block early

A return statement inside a with block, or a break in a loop around it, leaves the block early. The manager still releases its resource.

early_exit.py
def first_line(path):
    with open(path) as f:
        return f.readline().strip()


print(first_line("notes.txt"))

for name in ["log.txt", "notes.txt"]:
    with open(name) as f:
        line = f.readline().strip()
        if line.startswith("buy"):
            print("found in", name, "->", line)
            break
    print(name, "has no purchase")

print(name, "closed:", f.closed)

first_line returns from inside the block; the file is closed before the caller receives the line. The loop checks the first line of each file. In notes.txt the line matches, and break leaves both the with block and the loop. The file is closed even though the block did not reach its end.

$ python early_exit.py
buy coffee
log.txt has no purchase
found in notes.txt -> buy coffee
notes.txt closed: True

Several managers in one statement

One with statement can manage several resources. The managers are separated by commas and entered from left to right. When the block ends, they are exited in the reverse order.

two_files.py
with open("names.txt", "w") as f:
    f.write("lucia\npeter\nmonika\n")

with open("names.txt") as src, open("upper.txt", "w") as dst:
    for line in src:
        dst.write(line.upper())

print(src.closed, dst.closed)

with open("upper.txt") as f:
    print(f.read(), end="")

The program reads names from one file and writes them in upper case to another. Both files are open during the loop and both are closed afterwards. If opening the second file failed, the first one would still be closed. This form replaces two nested with statements.

$ python two_files.py
True True
LUCIA
PETER
MONIKA

Managers on several lines

Since Python 3.10, the managers can be enclosed in parentheses and split across several lines. A trailing comma after the last manager is allowed.

grouped.py
with (
    open("names.txt") as names,
    open("upper.txt") as upper,
    open("pairs.txt", "w") as out,
):
    for low, up in zip(names, upper):
        out.write(f"{low.strip()} = {up.strip()}\n")

with open("pairs.txt") as f:
    print(f.read(), end="")

Three files are opened in one statement: two for reading and one for writing. The zip function reads the two input files line by line in parallel, and each pair is written to pairs.txt. The parenthesised form is easier to read than one long line or a backslash continuation.

$ python grouped.py
lucia = LUCIA
peter = PETER
monika = MONIKA

The as target

The as clause receives the value returned by the manager's __enter__ method. For a file it is the file itself, but other managers may return something else, or nothing useful. The as clause is optional.

as_target.py
import threading
from decimal import Decimal, localcontext

lock = threading.Lock()

with lock as acquired:
    print("acquired:", acquired)
    print("locked inside:", lock.locked())

print("locked after:", lock.locked())

with lock:
    print("no as target needed")

with localcontext() as ctx:
    ctx.prec = 4
    print(Decimal(2).sqrt())

print(Decimal(2).sqrt())

A threading.Lock is acquired at the start of the block and released at its end. Its __enter__ method returns the result of the acquisition, True, not the lock. Usually the lock is used without as. decimal.localcontext returns a copy of the current decimal context. Changing its precision affects only the calculations inside the block; after the block, the original precision of 28 digits is restored.

$ python as_target.py
acquired: True
locked inside: True
locked after: False
no as target needed
1.414
1.414213562373095048801688724

Temporary directories

The tempfile.TemporaryDirectory manager creates a directory with a unique name and removes it, together with all its contents, when the block ends. The as target is the path of the directory.

temp_dir.py
import os
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "report.txt")
    with open(path, "w") as f:
        f.write("temporary data\n")
    print(os.listdir(tmp))
    print("exists inside:", os.path.exists(path))

print("exists after:", os.path.exists(tmp))

A file is written into the temporary directory and the directory listing shows it. After the block, the directory no longer exists. The same pattern is useful in tests that need files on disk. A nested with statement inside the block opens the file.

$ python temp_dir.py
['report.txt']
exists inside: True
exists after: False

Database transactions

What a manager does at the end of the block depends on the manager. A sqlite3 connection used in a with statement manages a transaction: it commits when the block succeeds and rolls back when an exception occurs. It does not close the connection.

sqlite_with.py
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE cities (name TEXT, population INTEGER)")

with conn:
    conn.execute("INSERT INTO cities VALUES ('Bratislava', 475503)")
    conn.execute("INSERT INTO cities VALUES ('Košice', 229040)")

try:
    with conn:
        conn.execute("INSERT INTO cities VALUES ('Prešov', 82696)")
        conn.execute("INSERT INTO towns VALUES ('Nitra', 76533)")
except sqlite3.OperationalError as e:
    print("error:", e)

for row in conn.execute("SELECT name FROM cities"):
    print(row[0])

conn.close()

The first block inserts two rows and commits them. In the second block, the first insert succeeds, but the second refers to a missing table and raises an OperationalError. The manager rolls back the whole transaction, so Prešov is not saved either. The connection is still open after both blocks: the query works, and close must be called explicitly. The documentation of each manager tells what its with block does.

$ python sqlite_with.py
error: no such table: towns
Bratislava
Košice

Source

The with statement, With statement context managers, PEP 343 – The with statement, How to use the connection context manager

In this article we have used the with statement to close files automatically, also after errors and early exits, compared it with try/finally, managed several resources in one statement, and used locks, decimal contexts, temporary directories, and sqlite3 transactions as context managers. The asynchronous variant, async with, is covered in Python async/await. See also Python context managers, Python open function, and Python exceptions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.