Sub topic 3
Closing files reliably with with
This chapter assumes you know basic Python syntax, the difference between str and bytes, and how try/except works. You have seen that open() returns a file object. Here you will learn why that object must be closed and how the with statement does it for you.
Why closing matters
A file object holds an operating system resource called a file descriptor. Each process has a limited number of them. Writes are also buffered: Python keeps data in memory and passes it to the operating system later. Closing the file flushes that buffer.
If you forget to close a file, three things can go wrong:
- Buffered data may never reach the disk, so the file ends up short or empty.
- Descriptors leak. A long-running program eventually fails with
OSError: [Errno 24] Too many open files. - On Windows, an open file cannot be deleted or renamed by other code.
CPython often closes a file when the last reference to it disappears. Other implementations do not promise this, and you cannot rely on the timing. Close files explicitly.
The manual approach and its flaw
The obvious fix is to call close() yourself:
f = open("notes.txt", "w", encoding="utf-8")
f.write("first line\n")
f.close()If write() raises an exception, the close() line never runs. Wrapping the code in try/finally solves that, but it is verbose:
f = open("notes.txt", "w", encoding="utf-8")
try:
f.write("first line\n")
finally:
f.close()The with statement
The with statement does the same job in fewer lines. It runs a setup step, executes the indented block, and always runs a cleanup step, even when the block raises an exception.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.writelines(["second line\n", "third line\n"])The name after as is the file object. When the block ends, Python closes the file. This is true if the block finishes normally, if it hits return, break or continue, or if it raises an error.
with open("notes.txt", encoding="utf-8") as f:
print(f.closed) # False: the file is open inside the block
print(f.closed) # True: it was closed when the block endedThe variable f still exists after the block, but the file behind it is closed. Calling f.read() now raises ValueError: I/O operation on closed file.
How it works internally
with relies on the context manager protocol. A context manager is an object with two methods:
__enter__()runs when the block starts. For files it returns the file object itself, which is whatas freceives.__exit__()runs when the block ends. For files it callsclose().
If the block raised an exception, __exit__() still runs, and then the exception continues to propagate. The file's __exit__() does not suppress errors.
Opening several files at once
One with statement can manage several files. They are closed in reverse order of opening.
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())Common mistakes
- Using the file after the block. Reading from
fonce the block has ended raisesValueError. Do all the work on the file inside the block, or read the data into a variable first. - Leaving the
open()call outsidewith. Writingf = open(...)and thenwith f:works, but it leaves a gap where an error would skip the cleanup. Putopen()in thewithline. - Putting
tryin the wrong place. Ifopen()itself fails, no file exists and there is nothing to close. CatchFileNotFoundErroraround the wholewithstatement, not inside it.
Summary
Use with open(...) as f: for every file you open. It guarantees the file is closed and its buffer flushed, even when an exception occurs.
Exercise
This code is meant to print the first line of data.txt. It fails with ValueError. Why, and how do you fix it? with open("data.txt", encoding="utf-8") as f: pass first = f.readline() print(first)
Show answer
The with block ends before readline() is called, so the file is already closed. Move the read inside the block (indent the readline() call under the with statement), or read the data inside the block and use the resulting string afterwards.
Exercise
A with block contains the line "raise RuntimeError". Is the file closed, and does the RuntimeError still reach the caller?
Show answer
Yes to both. The file's _exit_() method runs and closes the file, then the RuntimeError continues to propagate. The with statement does not suppress exceptions.