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.
with expression as name:
# use name
# clean-up has happened hereSome 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
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())
print("closed?", f.closed)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.
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())['water plants', 'pay rent']
3Two files in one with
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())HELLO WORLD
4Clean-up happens even after an error
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)error handled file closed: True
5Your own context manager
from contextlib import contextmanager
@contextmanager
def section(title):
print(f"--- {title} ---")
yield
print("--- end ---")
with section("Totals"):
print("Rent: 800")
print("Food: 350")--- 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.
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")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.