Skip to content

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.

Beginner 6 min read·Lesson 200 of 306 in Python Programming

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

Python
f = open("data.txt", "w", encoding="utf-8")
try:
f.write("important")
finally:
f.close()
  • close() flushes and releases the file.
  • Use finally so it always happens.
  • with does this automatically.

Code examples

Using a closed file

Python
f = open("c.txt", "w", encoding="utf-8")
f.write("data")
f.close()
print(f.closed)
try:
f.write("more")
except ValueError as e:
print(e)
Output
True
I/O operation on closed file.

Buffered data appears on close

Python
f = open("buf.txt", "w", encoding="utf-8")
f.write("buffered text")
with open("buf.txt", encoding="utf-8") as g:
print(repr(g.read()))
f.close()
with open("buf.txt", encoding="utf-8") as g:
print(repr(g.read()))
Output
''
'buffered text'

More examples

Closing even when an error occurs

Python
def save_lines(path, lines):
f = open(path, "w", encoding="utf-8")
try:
for line in lines:
if not isinstance(line, str):
raise TypeError(f"not text: {line!r}")
f.write(line + "\n")
finally:
f.close()
print("closed:", f.closed)
save_lines("ok.txt", ["a", "b"])
try:
save_lines("bad.txt", ["a", 42])
except TypeError as e:
print(e)
with open("bad.txt", encoding="utf-8") as f:
print(f.read().split())
Output
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:

TextOutput
closed: True
closed: True
not text: 42
['a']

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

f = open(path, "w")
process(f) # raises
f.close() # never runs

Prefer

with open(path, "w", encoding="utf-8") as f:
process(f)

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

  1. 1
    Open five files in a loop, write to each and make sure all are closed even if one write fails.
  2. 2
    Demonstrate 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?
Practise this module