The close() method of a Python file object flushes any buffered data to the operating system and releases the file handle. You should always make sure a file is closed, and the best way is the with statement, which closes it automatically even when an exception occurs.
Calling close() more than once is harmless, but reading or writing a closed file raises ValueError.
close() doesclose() is not enoughwith statementpathlibclose() doesWhen you write to a file, Python usually keeps the data in a buffer and only sends it to the operating system when the buffer fills or the file closes. close():
file.closed becomes True.Note that close() flushes to the operating system, not necessarily to the physical disk. Call os.fsync(file.fileno()) after file.flush() if you must guarantee durability, for example for a database or a journal.
close() is not enoughIf an exception happens between open() and close(), the close line never runs:
Open handles leak, and on Windows a file left open may be locked so other programs cannot delete it. CPython closes files when the object is garbage collected, but that timing is not guaranteed, and other implementations such as PyPy do not close promptly. Unclosed files also trigger a ResourceWarning when warnings are enabled, for example with python -X dev.
You can use try and finally to guarantee closing:
with statementThe with statement is shorter and does the same guarantee:
The file closes when the block ends, whether it ends normally, with return, or by an exception. This works because file objects are context managers: with calls file.__enter__() at the start and file.__exit__() at the end, and __exit__ calls close().
You can open several files in one statement:
Always pass encoding="utf-8" for text files. Python 3.15 is planned to make UTF-8 the default, but earlier versions use the platform locale, which differs between machines.
pathlibFor small files, pathlib hides the open and close completely:
Both methods open and close the file for you. For large files, stream with with open(...) and iterate over lines instead.
You can test the state with f.closed. Closing a file twice is safe, so cleanup code does not need to check first.
The same idea applies to sockets, database connections and temporary files. Use contextlib.closing() for objects that have a close() method but are not context managers:
open() without keeping the result, such as open("a.txt").read(). The handle is closed only when it is garbage collected.ValueError."b" mode for binary data. Use open(path, "rb") for images and archives.Following the with pattern avoids all of them. Linters such as Ruff and Pylint flag unclosed files as well.
close() if I use with?No. The with block calls it for you. Calling it yourself inside the block is allowed but unnecessary.
CPython usually closes it when the object is collected, but buffered writes may be delayed and handles may leak, which can hit the operating system limit on open files.
close() save data to disk?It flushes Python's buffer to the operating system. Use flush() plus os.fsync() to force the data onto the disk itself.
No. Call open() again to get a new file object.
close() flushes buffers and frees the file handle. Prefer with open(...) so closing happens even on errors, always set an encoding for text files, and use contextlib.closing() for other resources that have a close() method.