Module 13 · File Handling — topic 7 of 15
Closing files
Why files must be closed: flushing buffered data, releasing operating-system handles, the closed attribute, errors after closing, and closing reliably with try/finally.
Learning objectives
- Explain what closing a file does
- Close files reliably even when errors occur
- Recognise symptoms of unclosed files
Definition
Closing a file with f.close() flushes any buffered data to disk and releases the operating-system resources the file was using. After closing, the file object can no longer be read or written.
Introduction
A file left open may not have its last lines on disk yet, and the operating system limits how many files a program can have open. Closing files is part of finishing the job.
Why it matters
Unclosed files cause lost data, locked files on Windows and 'too many open files' crashes in long-running programs.
Detailed explanation
Writes are buffered: Python collects data in memory and writes it to disk in larger blocks. close() (or flush()) pushes the remaining data out.
Each open file uses an operating-system handle. Programs have a limited number; leaking them eventually causes OSError: Too many open files.
On Windows, an open file may be locked, preventing other programs from deleting or renaming it.
f.closed tells you whether the file has been closed. Operations on a closed file raise ValueError: I/O operation on closed file.
Calling close() more than once is harmless.
If an exception happens between open and close, a plain close() at the end is skipped. Use try/finally, or better, a with statement.
Python usually closes files when the file object is garbage-collected, but relying on that is fragile; close explicitly.
Syntax
- close() flushes and releases the file.
- Use finally so it always happens.
- with does this automatically.
Code examples
Using a closed file
True I/O operation on closed file.
Buffered data appears on close
'' 'buffered text'
More examples
Closing even when an error occurs
closed: True closed: True not text: 42 ['a']
Step-by-step explanation
- finally closes the file on success and on failure.
- The line written before the error is flushed to disk by close().
- The TypeError still reaches the caller after cleanup.
Expected output
Running “Closing even when an error occurs” prints exactly:
Practical applications
- Servers that open files per request must close them or eventually crash.
- Editors that save files and release locks for other programs.
Best practices
- Prefer with statements.
- Otherwise close in finally.
- Call flush() when other programs must see data before closing.
Common mistakes
close() skipped by an exception
Avoid
Prefer
A with statement closes the file even when process raises.
Important notes
- The next lesson shows with statements, the standard way to guarantee closing.
Key takeaways
- close() flushes data and frees resources.
- Closed files can't be used.
- Close in finally or use with.
Try it yourself
- 1Open five files in a loop, write to each and make sure all are closed even if one write fails.
- 2Demonstrate flush() making data visible before close().
Finished reading? Mark it complete to update your dashboard.
Suggested practice
8 questions cover the “File Handling” module. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?
- ModerateWhich mode creates a new file but fails if the file already exists?