Sub topic 3
Closing files reliably with with
This chapter assumes you can write Python functions and loops, know the difference between str and bytes, and can use try/except/finally. It also assumes you have seen open() return a file object. Here you will learn why a file must be closed, what with does to guarantee that, and which mistakes still break it.
Why closing matters
An open file is a connection between your program and the operating system. Closing it matters for three reasons.
- Buffered data. Python does not send every
write()straight to disk. Text is collected in a buffer and written in larger pieces.close()flushes the buffer. If the file is never closed or flushed, the last part of your output may never reach the disk. - Limited handles. The operating system limits how many files a process can have open at once. A loop that opens thousands of files without closing them eventually fails with
OSError: [Errno 24] Too many open files. - Locks and sharing. On Windows, an open file often cannot be deleted, renamed, or opened by another program. Other platforms have similar problems with network file systems.
CPython usually closes a file when the last reference to it disappears. That is an implementation detail. PyPy and other runtimes may delay it, and a reference kept in an exception traceback can keep the file open for a long time. Python also emits a ResourceWarning for files closed this way. Do not depend on it.
The manual approach and its flaw
The obvious fix is to call close() yourself:
f = open("log.txt", "w", encoding="utf-8")
f.write("start\n")
risky = int("not a number") # raises ValueError
f.write("done\n")
f.close() # never reachedThe exception skips f.close(). A try/finally block repairs this, because finally runs whether or not an exception occurred:
f = open("log.txt", "w", encoding="utf-8")
try:
f.write("start\n")
f.write("done\n")
finally:
f.close()This works, but you must remember it every time. The open() call must also stay outside the try. If open() fails, there is no file object, and f.close() in finally would raise a NameError that hides the real error.
The with statement
The with statement does the same job with less code:
with open("log.txt", "w", encoding="utf-8") as f:
f.write("start\n")
f.write("done\n")When the block ends, Python closes the file. It does this on normal completion and when the block exits through an exception. It also does it for return, break, and continue.
A file object is a context manager. This is any object with two special methods:
__enter__()runs when the block starts. For files it returns the file object itself, which is whyas fworks.__exit__(exc_type, exc, tb)runs when the block ends. For files it callsclose().
Checking the state of a file
The closed attribute tells you whether a file is closed. The name f stays bound after the block, but the file behind it is closed:
with open("demo.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
print(f.closed) # False
print(f.closed) # True
try:
f.write("more\n")
except ValueError as exc:
print(exc) # I/O operation on closed file.Using a file after its with block is one of the most common errors at this level. The fix is to do all the work that needs the file inside the block.
Exceptions inside the block
The with statement closes the file, but it does not swallow the exception. A file's __exit__ returns a false value, so the exception continues upward after the cleanup:
try:
with open("demo.txt", "w", encoding="utf-8") as f:
f.write("partial\n")
raise RuntimeError("boom")
except RuntimeError:
print("closed:", f.closed) # True
with open("demo.txt", encoding="utf-8") as g:
print(g.read()) # partialThe text written before the error is on disk, because closing flushed the buffer. This is the right behavior for a log, but it is a problem if you wanted all-or-nothing output. A file that holds half of your intended data is a valid, closed file. The last chapter of this tutorial covers writing through a temporary file for that case.
Several files in one statement
Separate the items with commas to open more than one file. They are closed in reverse order, so the last file opened is the first closed:
with open("input.txt", "w", encoding="utf-8") as f:
f.write("one\ntwo\n")
with open("input.txt", encoding="utf-8") as src, \
open("output.txt", "w", encoding="utf-8") as dst:
for line in src:
dst.write(line.upper())If opening the second file fails, Python still closes the first. From Python 3.10 you can wrap the items in parentheses instead of using a backslash:
with (
open("input.txt", encoding="utf-8") as src,
open("output.txt", "w", encoding="utf-8") as dst,
):
dst.write(src.read())A variable number of files
A with statement lists its files in the source code, so it cannot handle a list whose length is only known at run time. contextlib.ExitStack collects context managers as you go and closes them all at the end:
from contextlib import ExitStack
from pathlib import Path
names = ["a.txt", "b.txt", "c.txt"]
for name in names:
Path(name).write_text(name + "\n", encoding="utf-8")
with ExitStack() as stack:
files = [stack.enter_context(open(name, encoding="utf-8")) for name in names]
for f in files:
print(f.readline().rstrip())If the third open() fails, the stack still closes the two files already opened. A plain loop that appends files to a list and closes them afterward does not give you this guarantee.
Returning data versus returning the file
A function that opens a file in a with block must not return the file object. By the time the caller receives it, it is closed:
def open_notes():
with open("notes.txt", "w+", encoding="utf-8") as f:
f.write("data\n")
return f
f = open_notes()
print(f.closed) # True; f.read() would raise ValueErrorReturn the data instead, or let the caller own the file by returning open(...) without a with. A third choice is a generator. A generator keeps its with block suspended between items, so the file stays open while you iterate:
def lines(name):
with open(name, encoding="utf-8") as f:
for line in f:
yield line.rstrip("\n")
for text in lines("input.txt"):
print(text)If the loop stops early with break and you keep a reference to the generator, the file stays open until the generator is closed or garbage collected. Call gen.close(), or wrap it in contextlib.closing(...), when that matters.
Writing your own context manager
The same protocol works for anything that needs cleanup. The @contextmanager decorator turns a generator into a context manager. Code before yield is the setup, and code after yield in a finally block is the cleanup:
from contextlib import contextmanager
@contextmanager
def opened_for_log(name):
f = open(name, "a", encoding="utf-8")
try:
f.write("--- start ---\n")
yield f
finally:
f.write("--- end ---\n")
f.close()
with opened_for_log("session.log") as log:
log.write("working\n")Without the try/finally, an exception in the caller's block would skip the code after yield.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using the file after the `with` block | `ValueError: I/O operation on closed file` | Move the work inside the block |
| Calling `open()` in a loop without `with` | `Too many open files`, or missing data | Use `with` in the loop body |
| Putting `open()` inside `try` and `close()` in `finally` | `NameError` or `UnboundLocalError` hides the real error | Use `with` |
| Returning the file from a `with` block | The caller gets a closed file | Return the data, or use a generator |
| Expecting `with` to catch errors | Exception still reaches the caller | Add `try`/`except` around the `with` |
| Reading a file while another handle still has unflushed writes | Missing or stale text | Close the writer first, or call `flush()` |
Exercise
This function should return the number of lines in a file, but it fails. Explain why, then fix it. def countlines(name): with open(name, encoding="utf-8") as f: pass return sum(1 for in f)
Show answer
The with block ends at pass, so the file is closed before the return line runs. Iterating over a closed file raises ValueError: I/O operation on closed file. Move the counting inside the block:
def countlines(name):
with open(name, encoding="utf-8") as f:
return sum(1 for in f)
The return inside with is safe, because the file is closed after the value is computed.
Exercise
You need to merge a list of files, whose length is known only at run time, into one output file, with every file closed even if one of them is missing. Which tool do you use, and why does a plain loop with append-and-close-later not give the same guarantee?
Show answer
Use contextlib.ExitStack. Open the output file and then each input with stack.enter_context(open(...)) inside a single with ExitStack() as stack: block. If a later open() raises, the stack closes everything opened so far. With a plain loop that opens files into a list and closes them afterward, an exception during opening leaves the earlier files open, because the closing code is never reached unless you wrap it in try/finally.