Python with and Closing Files
What you will learn
- Why a file must be closed
close(), theclosedattribute, and using a closed filetry/finallyversuswith- Passing a file object to a function
io.StringIO: a file that lives in memory- Files and generators, and opening many files with
ExitStack
1. Why close a file?
Opening a file asks the operating system for a resource. If a program does not give it back:
- Written text may not reach the disk (it can sit in a buffer, lesson 15.2).
- The system allows only a limited number of open files per program; a loop that opens a file on every pass without closing can run out.
- On Windows, an open file usually cannot be deleted or renamed by anyone else.
- Other programs may see an incomplete file.
Python closes a file when the object is garbage-collected, but you cannot rely on when that happens. Close files explicitly, and the easiest way to make sure is with (lesson 14.6).
2. The file object
open() returns a file object with useful attributes:
f = open("fruits.txt", encoding="utf-8")
print(f.closed, f.name, f.mode, f.encoding)
print(f.readline().strip())
f.close()
print(f.closed)
False fruits.txt r utf-8
apple
True
f.closedtells whether the file is closed.f.name,f.modeandf.encodingecho how it was opened.- Calling
close()twice is harmless. - Using a closed file raises an error:
f.readline()
ValueError: I/O operation on closed file.
Quick check: after `f.close()`, what does `f.closed` give?
True.
3. Manual closing with try and finally
The manual and safe way, from lesson 14.3:
f = open("fruits.txt", encoding="utf-8")
try:
for line in f:
if line.startswith("b"):
raise RuntimeError("stop")
except RuntimeError:
pass
finally:
f.close()
print(f.closed)
True
Even though an error interrupted the loop, finally closed the file. The with statement does exactly this and takes only two lines:
with open("fruits.txt", encoding="utf-8") as f:
for line in f:
...
Prefer with, always. Write manual close() calls only in the rare case where the file must stay open across several functions or objects (and then close it in the object's own cleanup code).
4. A file is only open inside the block
After the with block, the file object still exists, but it is closed. Any work that needs the data must happen inside the block, or the data must be copied out first:
def process(path):
with open(path, encoding="utf-8") as f:
return [ln.strip() for ln in f] # a real list, made while open
print(process("fruits.txt"))
['apple', 'banana', 'cherry']
A common trap is keeping something lazy (lesson 12.6) that still needs the open file:
with open("fruits.txt", encoding="utf-8") as f:
gen = (ln.strip() for ln in f) # nothing has been read yet
print(list(gen))
ValueError: I/O operation on closed file.
The generator expression did no reading until list(gen), which happened after the file was closed. Either build the list inside the block, or make the generator function own the file:
def lines(path):
with open(path, encoding="utf-8") as f:
for ln in f:
yield ln.strip()
print(list(lines("fruits.txt")))
['apple', 'banana', 'cherry']
The with inside a generator keeps the file open while the generator is being consumed, and closes it when the generator finishes or is closed.
5. Passing file objects to functions
A function can take an open file instead of a file name. Then it works with any source of lines, not just files on disk:
def count_lines(file):
return sum(1 for _ in file)
with open("fruits.txt", encoding="utf-8") as f:
print(count_lines(f))
3
The caller opens and closes the file; the function only uses it. This follows the principle of doing one job (lesson 11.8) and makes testing easy, as the next section shows.
6. Files in memory: io.StringIO
io.StringIO is a file-like object that lives in memory. It supports read, readline, iteration, write and print(file=...):
import io
mem = io.StringIO("red car\nblue bike\n")
print([ln.split()[0].upper() for ln in mem])
out = io.StringIO()
print("hello", file=out)
out.write("world\n")
print(repr(out.getvalue()))
print(count_lines(io.StringIO("a\nb\nc")))
['RED', 'BLUE']
'hello\nworld\n'
3
Uses:
- Testing functions that read or write files, without touching the disk (lesson 18.2).
- Building text with file-style code, then taking it all with
getvalue(). io.BytesIOis the same for bytes (lesson 15.8).
The standard streams are file objects too: sys.stdout (what print writes to), sys.stderr (error messages) and sys.stdin:
import sys
sys.stdout.write("direct write\n")
print("to stderr", file=sys.stderr)
direct write
to stderr
(sys.stderr output appears in the terminal too, but it is a separate stream, which can be redirected on its own.)
7. Opening many files: ExitStack
A with statement can list a few files. When the number of files is not known in advance, use contextlib.ExitStack: it collects context managers and closes all of them at the end, in reverse order:
from contextlib import ExitStack
names = ["t0.txt", "t1.txt", "t2.txt"]
with ExitStack() as stack:
handles = [stack.enter_context(open(n, "w")) for n in names]
for i, h in enumerate(handles):
h.write(f"file {i}\n")
print([h.closed for h in handles])
print([open(n).read().strip() for n in names])
[True, True, True]
['file 0', 'file 1', 'file 2']
(Without ExitStack, three files opened in a list comprehension would all stay open until closed by hand: the same loop with plain open printed [False, False, False] for closed.)
Worked example: one summary function for any source
summarize takes any file-like object: it counts lines and words and finds the longest line. We try it on an in-memory file, a real file and two files opened together.
import io
import os
from contextlib import ExitStack
def summarize(file):
"""Count lines, words and the longest line of any file-like object."""
lines = words = 0
longest = ""
for line in file:
line = line.rstrip("\n")
lines += 1
words += len(line.split())
if len(line) > len(longest):
longest = line
return {"lines": lines, "words": words, "longest": longest}
fake = io.StringIO("one two\nthree\nfour five six\n")
print(summarize(fake))
with open("poem.txt", "w", encoding="utf-8") as f:
f.write("roses are red\nviolets are blue\n")
with open("poem.txt", encoding="utf-8") as f:
print(summarize(f))
with open("a.txt", "w", encoding="utf-8") as f:
f.write("x y\n")
with open("b.txt", "w", encoding="utf-8") as f:
f.write("p\nq\nr\n")
with ExitStack() as stack:
handles = [stack.enter_context(open(n, encoding="utf-8")) for n in ("a.txt", "b.txt")]
for h in handles:
print(h.name, summarize(h)["lines"])
print([h.closed for h in handles])
for n in ("poem.txt", "a.txt", "b.txt"):
os.remove(n)
{'lines': 3, 'words': 6, 'longest': 'four five six'}
{'lines': 2, 'words': 6, 'longest': 'violets are blue'}
a.txt 1
b.txt 3
[True, True]
| Step | Idea |
|---|---|
summarize(file) gets an open file |
the function does not care where the lines come from |
io.StringIO |
a test with no file on disk |
a normal with open(...) |
the usual real use |
ExitStack |
several files, all closed together at the end |
os.remove |
cleanup works because every file is closed (important on Windows) |
The text is made up.
Common mistakes
- Not closing files (or not using
with). - Using a file after its
withblock, or returning a lazy object that needs it. - Opening files in a loop without closing them.
- Forgetting that
close()is needed to save buffered text when not usingwith. - Trying to delete or rename an open file (fails on Windows).
- Building a function that opens the file itself, which makes it hard to test.
Key takeaways
- Always close files;
with open(...) as f:does it for you, even after errors. - A closed file raises
ValueErrorif used;f.closedtells its state. - Do the reading inside the block or build a real list there; do not leave lazy objects that need the open file.
- Functions that accept a file object are flexible and easy to test, for example with
io.StringIO. ExitStackopens and closes any number of files together.
Practice
1. Name two problems caused by not closing a file.
Show answer
Written text may stay in the buffer and never reach the disk; the program may run out of allowed open files; on Windows the file cannot be deleted or renamed.
2. What does with open(...) as f: do that a plain open(...) does not?
Show answer
It closes the file automatically when the block ends, whether normally or because of an error.
3. Why does list(gen) fail in the generator-expression example?
Show answer
The generator reads lazily, and by the time it runs the with block has closed the file.
4. What is io.StringIO used for?
Show answer
A file-like object stored in memory, handy for tests and for building text with file-style code.
5. Write a function longest_line(file) that returns the longest line of any file object.
Show answer
def longest_line(file):
return max((ln.rstrip("\n") for ln in file), key=len, default="")
6. When would you use ExitStack?
Show answer
When the number of files (or other context managers) is not known in advance, and they must all be closed at the end.