Statement

with statement

with sets something up, runs your block, then always cleans up, even after an error. It is the standard way to open files.

IntermediateEvery example below runs in your browser. Change the code and press Run.

with expression as name: # use name # clean-up has happened here

Some things must be closed or released when you are done: files, network connections, locks. with takes care of that. When the indented block ends, normally or because of an error, the clean-up runs automatically.

The object after with is called a context manager. open() returns one, so with open("notes.txt") as f: opens the file, gives it the name f, and closes it at the end of the block.

You can open several things in one with, separated by commas, and you can write your own context managers with a class or with contextlib.contextmanager.

Examples

1Read a file

Pythoneditable
with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
print("closed?", f.closed)
Output
buy milk
call Rosa
closed? True

After the block, the file is already closed. You never call f.close() yourself.

2Write a file, then read it back

Mode "w" creates the file, or empties it if it exists.

Pythoneditable
with open("todo.txt", "w", encoding="utf-8") as f:
    f.write("water plants\n")
    f.write("pay rent\n")

with open("todo.txt", encoding="utf-8") as f:
    print(f.read().splitlines())
Output
['water plants', 'pay rent']

3Two files in one with

Pythoneditable
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())

with open("out.txt", encoding="utf-8") as f:
    print(f.read().strip())
Output
HELLO
WORLD

4Clean-up happens even after an error

Pythoneditable
try:
    with open("data.txt", encoding="utf-8") as f:
        first = f.readline()
        raise ValueError("bad data")
except ValueError:
    print("error handled")
print("file closed:", f.closed)
Output
error handled
file closed: True

5Your own context manager

Pythoneditable
from contextlib import contextmanager

@contextmanager
def section(title):
    print(f"--- {title} ---")
    yield
    print("--- end ---")

with section("Totals"):
    print("Rent: 800")
    print("Food: 350")
Output
--- Totals ---
Rent: 800
Food: 350
--- end ---

The code before yield runs on entry, the code after it on exit.

Common mistakes

Using the file after the block

The file is closed when the with block ends. Reading from it afterwards fails, so do all the work inside the block, or store what you need in a variable.

Pythoneditable
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
try:
    f.read()
except ValueError:
    print("ValueError: the file is already closed")
Output
ValueError: the file is already closed

Forgetting the encoding

Without encoding="utf-8", open() uses the system's default, which differs between Windows, Mac and Linux. Accented letters may then come out wrong.

Questions people ask

Why use with open instead of open and close?

If an error happens before close(), the file stays open. with closes it in every case, with less code.

How do I append to a file?

Open it with mode "a": with open("log.txt", "a") as f: f.write("new line\n").

What is a context manager?

Any object with __enter__ and __exit__ methods. with calls the first at the start and the second at the end.

Spotted a mistake on this page? Tell us