To close a file in Python, call close() on the file object, or use a with block, which closes it for you even after an error:
with open("orders.txt", encoding="utf-8") as f:
data = f.read()
print(f.closed) # True
My machine for these runs is Python 3.12.5 on Windows 11, which matters for the Windows lock section.
In this tutorial, we’ll look at close(), the closed attribute, flush versus close, try/finally, and what goes wrong when you leave a file open.
Close a file with close() and check the closed attribute
close() writes out buffered data and frees the OS handle. Opening modes are covered in opening a file in Python.
f = open("orders.txt", "w", encoding="utf-8")
print("closed before:", f.closed)
f.write("1001,Emily Carter,49.99\n")
f.close()
print("closed after: ", f.closed)
f.close() # a second close() does nothing
try:
f.write("1002,James Lee,15.00\n")
except ValueError as err:
print("ValueError:", err)
Output:
closed before: False
closed after: True
ValueError: I/O operation on closed file.

closed flips to True, a second close() is harmless, and writing afterwards raises ValueError.If you ever see “I/O operation on closed file”, a read or write sits outside the block that owned the file.
What’s the difference between flush() and close()?
Writes land in a memory buffer first. flush() pushes it to disk and keeps the file open; close() flushes, then shuts it. A second reader checks the file between steps:
log = open("sales_log.txt", "w", encoding="utf-8")
log.write("2026-03-02,Emily Carter,129.50\n")
with open("sales_log.txt", encoding="utf-8") as reader:
print("before flush:", repr(reader.read()))
log.flush()
with open("sales_log.txt", encoding="utf-8") as reader:
print("after flush: ", repr(reader.read()))
log.write("2026-03-03,James Lee,88.25\n")
log.close() # close() flushes the rest first
with open("sales_log.txt", encoding="utf-8") as reader:
print("after close: ", reader.read().count("\n"), "lines on disk")
Output:
before flush: ''
after flush: '2026-03-02,Emily Carter,129.50\n'
after close: 2 lines on disk

flush(), and the second line only lands after close().That’s why a log can look empty while your script runs. You’ll want flush() in long-running writers. More on writing text is in writing a string to a file in Python.
Close a file safely with try/finally
If an exception fires before close(), that line never runs, but finally always does. Here the second order’s amount is N/A:
with open("orders.txt", "w", encoding="utf-8") as out:
out.write("1001,Emily Carter,49.99\n1002,James Lee,N/A\n")
def load_orders(path):
f = open(path, encoding="utf-8")
try:
return [float(line.split(",")[2]) for line in f]
finally:
f.close()
print("finally ran, closed =", f.closed)
try:
load_orders("orders.txt")
except ValueError as err:
print("caught:", err)
Output:
finally ran, closed = True
caught: could not convert string to float: 'N/A\n'
The file was closed before the caller caught the error. For several error types, see catching multiple exceptions in Python.
Let the with statement close files automatically
A with block is that same try/finally, written for you:
try:
with open("orders.txt", "w", encoding="utf-8") as f:
f.write("1001,Emily Carter,49.99\n")
raise RuntimeError("payment API timed out")
except RuntimeError as err:
print("error:", err, "| closed:", f.closed)
Output:
error: payment API timed out | closed: True
The file closed even though the block raised. I use with for nearly every file; the full guide is Python with open.
What happens if you don’t close a file?
CPython usually closes a forgotten file during garbage collection. It’s still a bug, and Python flags it as a ResourceWarning once you turn warnings on:
import warnings
warnings.simplefilter("default") # ResourceWarning is hidden unless you turn it on
with open("orders.txt", "w", encoding="utf-8") as f:
f.write("1001,Emily Carter,49.99\n1002,James Lee,15.00\n")
def count_orders(path):
f = open(path, encoding="utf-8") # opened, never closed
return len(f.readlines())
print("orders:", count_orders("orders.txt"))
Output:
C:\pyguides\unclosed_warning.py:11: ResourceWarning: unclosed file <_io.TextIOWrapper name='orders.txt' mode='r' encoding='utf-8'>
print("orders:", count_orders("orders.txt"))
ResourceWarning: Enable tracemalloc to get the object allocation traceback
orders: 2

orders.txt was never closed.A crash can lose unflushed data. Run tests with python -W default to catch leaks. Other file object methods are in Python file methods.
Why can’t Windows delete a file I didn’t close?
Windows locks a file while it’s open, so deleting or renaming it fails with WinError 32. Linux and macOS allow it, so the bug hides until you run on Windows:
import os
f = open("report_2026.csv", "w", encoding="utf-8")
f.write("region,total\nEast,1250.00\n")
try:
os.remove("report_2026.csv")
except PermissionError as err:
print("PermissionError:", err)
f.close()
os.remove("report_2026.csv")
print("deleted after close:", not os.path.exists("report_2026.csv"))
Output:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'report_2026.csv'
deleted after close: True

os.remove() fails while the file is open and works right after close().With WinError 32, hunt for the open handle, sometimes in Excel. Safe delete patterns are in deleting a file if it exists in Python.
Next on the file-handling list:
- Read a file line by line in Python
- Write multiple lines to a file in Python
- Check if a file exists in Python
- Create a new file in Python
Frequently asked questions
How do I close a file in Python?
Call f.close(), or use with open(...) as f:.
How do I check if a file is closed?
Check f.closed; it’s True once closed.
Does the with statement close the file on an error?
Yes, it closes on any exit, including exceptions.
Is it an error to call close() twice?
No, the second call does nothing.
Does close() save the data?
Yes, it flushes buffered writes first. flush() saves without closing.
Where is file close() documented?
See io.IOBase.close() in the Python docs.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn