Python file.close() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
file method

Definition

close() finishes working with a file: it flushes any buffered writes, then gives the file back to the operating system. Afterwards f.closed is True.

Calling it a second time is harmless. Using the file after closing, for reading, writing, or seeking, raises ValueError: I/O operation on closed file.

file.close() is a method of the file objects that the built-in open() returns, so no import is needed. It works on text files (TextIOWrapper), binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).

Syntax

Call it directly, or let a with block call it for you.

python
f = open(path, "w", encoding="utf-8")
f.write("data\n")
f.close()
CallWhat it does
f.close()Flushes and closes; returns None.
f.close()Again on a closed file: does nothing, no error.
with open(path) as f:Closes automatically when the block ends, even on an exception.

f.closed is an attribute, not a method: write f.closed, not f.closed().

Method signatures
python
file.close()   # -> None
# file.closed -> bool attribute

Parameters

close() takes no parameters.

Return Value

Return ValueDescription
NoneAlways. If the final flush fails, for example on a full disk, OSError is raised but the file is still marked closed.

Python Examples

Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.

Example 1 — Close a Receipt File by Hand

Open without with, close twice, and try one more write.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "receipt.txt")
    f = open(path, "w", encoding="utf-8")
    f.write("total=12\n")
    print(f.closed)
    print(f.close(), f.closed)
    f.close()
    try:
        f.write("tip=2\n")
    except ValueError:
        print("writing to a closed file raises ValueError")
    with open(path, encoding="utf-8") as check:
        print(repr(check.read()))

How It Works

  1. Open by hand. Without with, the file stays open until close() is called, and f.closed is False.
  2. Returns None. close() returns nothing useful; afterwards f.closed flips to True.
  3. Idempotent. The second close() does nothing and raises nothing.
  4. Data kept, writes refused. The new write raises ValueError, while the line written before closing was flushed and is still there.

Example 2 — Show That with Closes Even After an Error

Sum ages from a file until a bad line raises, then check whether the file is closed.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "ages.txt")
    with open(path, "w", encoding="utf-8") as f:
        f.write("31\nforty\n")

    total = 0
    try:
        with open(path, encoding="utf-8") as f:
            for line in f:
                total += int(line)
    except ValueError:
        print("bad number after a total of", total)
    print("file closed anyway:", f.closed)

How It Works

  1. First line parses. int("31\n") ignores the surrounding whitespace, so the total becomes 31.
  2. Second line fails. int("forty\n") raises ValueError in the middle of the with block.
  3. Exit still closes. Leaving the block because of the exception still calls close(), so f.closed is True.

Example 3 — Close in finally When You Cannot Use with

A report writer that closes its file in finally, even when a bad row raises.

python
import os
import tempfile


def save_report(path, rows):
    f = open(path, "w", encoding="utf-8")
    try:
        for row in rows:
            f.write(row + "\n")
    finally:
        f.close()
    return f.closed


with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "report.txt")
    print(save_report(path, ["north 4", "south 2"]))
    try:
        save_report(path, ["east 7", None])
    except TypeError:
        print("row 2 failed, but the file was still closed")
    with open(path, encoding="utf-8") as f:
        print(f.read().splitlines())

How It Works

  1. Manual pattern. try/finally is what a with block does for you behind the scenes.
  2. Happy path. The first call writes both rows and returns f.closed, which is True.
  3. Failure path. None + "\n" raises TypeError, but finally still closes the file before the error reaches the caller.
  4. Partial output survives. Closing flushed the one row written before the error, so the file holds east 7; "w" had already erased the older rows.

Frequently Asked Questions

No. The with statement calls close() automatically when the block ends, whether normally or because of an exception.
Buffered data may never be written, the file may stay locked on Windows, and a long-running program can run out of file descriptors. CPython often closes it when the object is garbage collected, but do not rely on that.
You read, wrote, or seeked after the file was closed, often because the code ran after the with block ended. Move the code inside the block.
No. close() on an already closed file does nothing.
Read the f.closed attribute. It is True after close() and False while the file is open.

Next: file.detach()

Separate a text or buffered stream from the layer below it and return that layer.

detach() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful