close() finishes working with a file: it flushes any buffered writes, then gives the file back to the operating system. Afterwards f.closed is True.
Calling it a second time is harmless. Using the file after closing, for reading, writing, or seeking, raises ValueError: I/O operation on closed file.
file.close() is a method of the file objects that the built-in open() returns, so no import is needed. It works on text files (TextIOWrapper), binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).
Syntax
Call it directly, or let a with block call it for you.
python
f = open(path, "w", encoding="utf-8")
f.write("data\n")
f.close()
Call
What it does
f.close()
Flushes and closes; returns None.
f.close()
Again on a closed file: does nothing, no error.
with open(path) as f:
Closes automatically when the block ends, even on an exception.
f.closed is an attribute, not a method: write f.closed, not f.closed().
Always. If the final flush fails, for example on a full disk, OSError is raised but the file is still marked closed.
Python Examples
Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.
Example 1 — Close a Receipt File by Hand
Open without with, close twice, and try one more write.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "receipt.txt")
f = open(path, "w", encoding="utf-8")
f.write("total=12\n")
print(f.closed)
print(f.close(), f.closed)
f.close()
try:
f.write("tip=2\n")
except ValueError:
print("writing to a closed file raises ValueError")
with open(path, encoding="utf-8") as check:
print(repr(check.read()))
Output
False
None True
writing to a closed file raises ValueError
'total=12\n'
How It Works
Open by hand. Without with, the file stays open until close() is called, and f.closed is False.
Returns None.close() returns nothing useful; afterwards f.closed flips to True.
Idempotent. The second close() does nothing and raises nothing.
Data kept, writes refused. The new write raises ValueError, while the line written before closing was flushed and is still there.
Example 2 — Show That with Closes Even After an Error
Sum ages from a file until a bad line raises, then check whether the file is closed.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "ages.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("31\nforty\n")
total = 0
try:
with open(path, encoding="utf-8") as f:
for line in f:
total += int(line)
except ValueError:
print("bad number after a total of", total)
print("file closed anyway:", f.closed)
Output
bad number after a total of 31
file closed anyway: True
How It Works
First line parses.int("31\n") ignores the surrounding whitespace, so the total becomes 31.
Second line fails.int("forty\n") raises ValueError in the middle of the with block.
Exit still closes. Leaving the block because of the exception still calls close(), so f.closed is True.
Example 3 — Close in finally When You Cannot Use with
A report writer that closes its file in finally, even when a bad row raises.
python
import os
import tempfile
def save_report(path, rows):
f = open(path, "w", encoding="utf-8")
try:
for row in rows:
f.write(row + "\n")
finally:
f.close()
return f.closed
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "report.txt")
print(save_report(path, ["north 4", "south 2"]))
try:
save_report(path, ["east 7", None])
except TypeError:
print("row 2 failed, but the file was still closed")
with open(path, encoding="utf-8") as f:
print(f.read().splitlines())
Output
True
row 2 failed, but the file was still closed
['east 7']
How It Works
Manual pattern.try/finally is what a with block does for you behind the scenes.
Happy path. The first call writes both rows and returns f.closed, which is True.
Failure path.None + "\n" raises TypeError, but finally still closes the file before the error reaches the caller.
Partial output survives. Closing flushed the one row written before the error, so the file holds east 7; "w" had already erased the older rows.
Frequently Asked Questions
No. The with statement calls close() automatically when the block ends, whether normally or because of an exception.
Buffered data may never be written, the file may stay locked on Windows, and a long-running program can run out of file descriptors. CPython often closes it when the object is garbage collected, but do not rely on that.
You read, wrote, or seeked after the file was closed, often because the code ran after the with block ended. Move the code inside the block.
No. close() on an already closed file does nothing.
Read the f.closed attribute. It is True after close() and False while the file is open.