Python close function
last modified November 29, 2026 Python 3.15
In this article we show how to close a file object and what happens afterwards. We look at the closed attribute, repeated close calls, errors on a closed file, the with statement, flushing, and why deleting a name is not the same as closing.
Files are opened as described in Python open function. Writing is covered in Python write function and flushing without closing in Python flush function.
The text file
Most examples open and close the same small file of city names, saved in UTF-8 with one name per line.
Paris Prague Vienna Kraków Budapest Warsaw
The accented ó in Kraków takes two bytes in UTF-8 but counts as a single character, which matters for every method that counts one or the other.
Closing a file
close releases the operating system resource behind the file object and marks the object as closed. The closed attribute reports the state.
f = open('cities.txt', encoding='utf-8')
print(f.closed)
f.close()
print(f.closed)
Before the call closed is False; afterwards it is True. The object still exists and can be inspected, but it no longer refers to an open file.
$ python close_file.py False True
Calling close twice
close is idempotent: calling it on an already closed file does nothing and does not raise.
f = open('cities.txt', encoding='utf-8')
f.close()
f.close()
print(f.closed)
Only one line is printed, and the file stays closed. Code that closes in a finally block and also in the normal flow therefore does not need a guard for this case.
$ python close_twice.py True
Using a closed file
Reading, writing, or reading a line after close raises ValueError. The check happens in Python before any system call.
f = open('cities.txt', encoding='utf-8')
f.close()
try:
f.read()
except ValueError as e:
print(type(e).__name__, e)
try:
f.write('milk\n')
except ValueError as e:
print(type(e).__name__, e)
Both calls produce the same message, I/O operation on closed file.. This is ValueError, not OSError. A file opened only for reading and then written to raises UnsupportedOperation instead, which is a subclass of both; Python open function shows that case.
$ python close_use.py ValueError I/O operation on closed file. ValueError I/O operation on closed file.
The with statement
The with statement closes the file when the block ends, including when the block raises an exception.
try:
with open('cities.txt', encoding='utf-8') as f:
print(f.readline().rstrip())
raise RuntimeError('stop')
except RuntimeError:
print('caught')
print(f.closed)
The first line is read, the exception is caught outside the block, and f.closed is True. The close happens while the with block unwinds, before the except clause runs, so the file cannot leak because of the error.
$ python close_with.py Paris caught True
Closing flushes the buffer
close first flushes the write buffer and then releases the file. Data written just before the call is therefore in the file when it returns.
f = open('notes.txt', 'w', encoding='utf-8')
f.write('milk\n')
print(f.closed)
f.close()
with open('notes.txt', encoding='utf-8') as g:
print(repr(g.read()))
print(g.closed)
closed is False while the file is open, the read after the close returns milk\n, and the reader itself is closed at the end of its block. Python flush function shows how to push the same data out without closing.
$ python close_flush.py False 'milk\n' True
Deletion is not closing
Deleting a name does not close the file. The object is closed only when its last reference disappears, through a destructor whose timing the language does not guarantee.
f = open('cities.txt', encoding='utf-8')
alias = f
del f
print(alias.closed)
alias.close()
print(alias.closed)
After del f the alias still refers to the object, so closed is False; only close, or the end of the object's life, changes that. Depending on __del__ is unsafe: reference cycles delay it, another implementation may collect later, and it may not run at interpreter shutdown.
$ python close_delete.py False True
Two files at once
A single with statement can manage several files. They are closed in the reverse order of opening when the block ends.
with open('cities.txt', encoding='utf-8') as src, open('copy.txt', 'w', encoding='utf-8') as dst:
dst.write(src.read())
print(src.closed, dst.closed)
with open('copy.txt', encoding='utf-8') as f:
print(f.read().startswith('Paris'))
Both objects report closed after the block, and the copy starts with Paris. If the second open failed, the with machinery would still close the first file.
$ python close_two.py True True True
Source
IOBase.close – Python documentation
The with statement – Python Language Reference
In this article we have closed files explicitly and with with, checked closed, seen the ValueError that follows misuse, and learned why deletion cannot replace a close. See also Python open function, Python flush function, and Python write function.
Author
List all Python tutorials.