🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

close()

AI & DATA SCIENCE // close

file.close() closes an open file, flushing any buffered writes to disk and releasing the underlying operating system file handle.

Syntax

f = open("file.txt")
# ... use f ...
f.close()

Deep Dive Course

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.

editor.html
f = open("temp.txt", "w")
f.write("data")
f.close()
print(f.closed)
localhost:3000

2Practical Example

Here is a real-world application of close() showing how it is used in production Python code.

editor.html
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")
localhost:3000

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.

editor.html
f = open("temp.txt", "w")
f.write("data")
f.close()
print(f.closed)
localhost:3000

Examples

Example 01Basic Usage
f = open("temp.txt", "w")
f.write("data")
f.close()
print(f.closed)
Example 02Advanced Example
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")

Best Practices

  • Use a with block instead of a manual close() call whenever possible, so the file closes automatically even on error
  • If you must call close() manually, wrap the file operations in try/finally so close() still runs if an exception occurs
  • Don't rely on a file being closed automatically by garbage collection — that timing isn't guaranteed, especially on implementations other than CPython

Interview Question

Why can forgetting to close a file cause data loss even if you never got an explicit error?

Hint: Think about what happens to data written with write() before close() is called.

Writes made with write() aren't necessarily sent to disk immediately — they can sit in an internal buffer for efficiency, batched up and flushed together later. Closing the file explicitly flushes that buffer, guaranteeing everything written actually reaches disk. If the program exits or crashes before the file is closed, buffered data that was never flushed can be silently lost, even though the write() calls themselves appeared to succeed without raising any error.

Exercises

MediumPractice using close() in a real scenario.
View Solution
f = open("temp.txt", "w")
f.write("data")
f.close()
print(f.closed)

Frequently Asked Questions

Why can forgetting to close a file cause data loss even if you never got an explicit error?

Writes made with write() aren't necessarily sent to disk immediately — they can sit in an internal buffer for efficiency, batched up and flushed together later. Closing the file explicitly flushes that buffer, guaranteeing everything written actually reaches disk. If the program exits or crashes before the file is closed, buffered data that was never flushed can be silently lost, even though the write() calls themselves appeared to succeed without raising any error.

Related Functions

open()with-statementwrite()