Closing a file is important for two reasons: it flushes any data still sitting in an internal write buffer out to disk, since without closing, buffered writes might never actually reach the file, and it releases the operating system's file handle, which is a limited resource — leaving many files open can eventually exhaust the OS's per-process file descriptor limit. Calling close() more than once is safe and does nothing on subsequent calls. Once a file is closed, further reads or writes on it raise a ValueError.
1Understanding close()
Closing a file is important for two reasons: it flushes any data still sitting in an internal write buffer out to disk, since without closing, buffered writes might never actually reach the file, and it releases the operating system's file handle, which is a limited resource — leaving many files open can eventually exhaust the OS's per-process file descriptor limit. Calling close() more than once is safe and does nothing on subsequent calls. Once a file is closed, further reads or writes on it raise a ValueError.
Prefer a `with` block over manually calling close() — it guarantees the file closes even if an exception happens in between, which a manual close() call, placed after the code that might fail, would never reach.
f = open("temp.txt", "w")
f.write("data")
f.close()
print(f.closed)2Practical Example
Here is a real-world application of close() showing how it is used in production Python code.
f = open("temp.txt", "w")
try:
f.write("data")
raise ValueError("Something went wrong")
except ValueError:
pass
finally:
f.close()
print("File closed even though an error occurred")3Best Practices
Follow these guidelines when working with close():
1. Use a with block instead of a manual close() call whenever possible, so the file closes automatically even on error
2. If you must call close() manually, wrap the file operations in try/finally so close() still runs if an exception occurs
3. Don't rely on a file being closed automatically by garbage collection — that timing isn't guaranteed, especially on implementations other than CPython
Tip: Prefer a `with` block over manually calling close() — it guarantees the file closes even if an exception happens in between, which a manual close() call, placed after the code that might fail, would never reach.
f = open("temp.txt", "w")
f.write("data")
f.close()
print(f.closed)