Sub topic 1
What open() returns
Most Python programs touch files through one call: open(). The call does not return the file's contents. It returns a file object, which is a handle you use to read, write, and close the file. This chapter explains what that object is, which layers it is built from, and what state it carries. Knowing this explains many later behaviors, including why data sometimes does not appear on disk when you expect it.
Prerequisites
This chapter assumes you already know:
- Basic Python syntax: variables, functions, loops, and attribute access such as
obj.name. - The difference between
str(text) andbytes(raw data). - How
try/exceptworks.
You do not need to know file modes, the with statement, or pathlib. Later chapters cover them. This chapter touches each only as far as needed.
A handle, not the data
Calling open() asks the operating system for access to a file. If the request succeeds, Python wraps the result in an object and returns it. Nothing has been read yet. The file object tracks:
- Which file it refers to.
- Whether you may read, write, or both.
- A current position, meaning where the next read or write happens.
- Buffers holding data on its way in or out.
f = open("notes.txt", "w", encoding="utf-8")
print(f)
print(f.name)
print(f.mode)
print(f.encoding)
print(f.closed)
f.close()
print(f.closed)The print(f) line shows something like <_io.TextIOWrapper name='notes.txt' mode='w' encoding='utf-8'>. The other lines print notes.txt, w, utf-8, False, and then True.
Three attributes appear here:
nameis the path you passed in.modeis the mode string you passed.closedisTrueonce the file has been closed.
The encoding attribute exists only on text files. Binary files have no encoding because they deal in raw bytes.
Three layers inside one object
The object that open() returns is usually the top of a stack of three objects from the standard io module. Each layer does one job.
| Layer | Class | Job |
|---|---|---|
| Text | `TextIOWrapper` | Converts between `str` and `bytes` using the encoding, and translates newlines |
| Buffer | `BufferedReader`, `BufferedWriter`, `BufferedRandom` | Collects bytes in memory so the program makes fewer system calls |
| Raw | `FileIO` | Talks to the operating system through a file descriptor |
You can walk down the stack through the buffer and raw attributes:
f = open("notes.txt", "w", encoding="utf-8")
print(type(f))
print(type(f.buffer))
print(type(f.buffer.raw))
f.close()This prints:
<class '_io.TextIOWrapper'>
<class '_io.BufferedWriter'>
<class '_io.FileIO'>Which object you get back depends on the mode string:
| Call | Type returned |
|---|---|
| `open(p, "r")`, `open(p, "w")`, `open(p, "r+")` | `TextIOWrapper` |
| `open(p, "rb")` | `BufferedReader` |
| `open(p, "wb")` or `open(p, "ab")` | `BufferedWriter` |
| `open(p, "r+b")` or `open(p, "w+b")` | `BufferedRandom` |
| `open(p, "rb", buffering=0)` | `FileIO` |
The pattern is simple. Without a b in the mode you get the text layer on top. With b you get the buffer layer on top, because binary data needs no decoding. The next chapter covers what each mode letter means. For now, note that the mode controls which class you receive.
Why the layers matter
Each layer has its own methods. TextIOWrapper.read() returns str. BufferedReader.read() returns bytes. If you have a text file object and need the underlying bytes, f.buffer gives you the binary layer. Mixing the two layers on one file is rarely a good idea, because the text layer keeps its own pending data and the position can become confusing.
You can also ask for no buffering at all:
raw = open("notes.txt", "rb", buffering=0)
print(type(raw))
raw.close()This returns a bare FileIO. Text mode with buffering=0 is not allowed and raises ValueError, because the text layer needs a buffer beneath it.
The file descriptor underneath
At the bottom of the stack, the operating system identifies an open file with a small integer called a file descriptor. FileIO holds that integer, and you can read it:
f = open("notes.txt", "r", encoding="utf-8")
print(f.fileno())
f.close()The number is usually 3 or higher in a simple script, because 0, 1, and 2 are already taken by standard input, standard output, and standard error. You rarely need the number directly. It matters for two reasons.
- Functions such as
os.fsync()take a descriptor. The safe-write chapter uses this. - Descriptors are a limited resource. Each process may have only so many open at once, often 1024 by default on Linux. Opening files in a loop without closing them eventually fails with
OSError: [Errno 24] Too many open files.
Buffering: why data is not on disk yet
The buffer layer is the main source of surprise for new users. When you call write(), the data usually goes into a memory buffer first. The buffer is sent to the operating system when it fills up (the default size is io.DEFAULT_BUFFER_SIZE, 8192 bytes), when you call flush(), or when you close the file.
import os
f = open("demo.txt", "w", encoding="utf-8")
f.write("hello")
print(os.path.getsize("demo.txt"))
f.flush()
print(os.path.getsize("demo.txt"))
f.close()On most systems this prints 0 and then 5. Before flush(), the five bytes sit in Python's buffers and the file on disk is still empty. Another program reading the file at that moment would see nothing.
flush() has a limit. It moves data from Python's buffers to the operating system, but the operating system may still hold it in its own cache. Only os.fsync() asks the OS to push it to the physical disk. Ordinary scripts do not need that. Programs that must survive a power failure do.
State: position, exhaustion, and closing
The file keeps a position
A file object remembers where it is. Reading moves the position forward, and a later read continues from there. A file object is also its own iterator, so looping over it consumes it:
f = open("notes.txt", "w", encoding="utf-8")
f.write("one\ntwo\n")
f.close()
f = open("notes.txt", encoding="utf-8")
print(iter(f) is f)
print(list(f))
print(list(f))
f.close()The output is:
True
['one\n', 'two\n']
[]The second list(f) returns an empty list because the first call used up the file. The position is now at the end. This is not an error. It is the normal behavior of any iterator. To read the file again, open it again, or move the position back with seek(), which a later chapter covers.
A closed file cannot be used
After close(), the file object still exists but the descriptor is released. Using the object raises an error:
f = open("notes.txt", encoding="utf-8")
f.close()
f.close()
print(f.closed)
try:
f.read()
except ValueError as err:
print(err)The output is:
True
I/O operation on closed file.Calling close() twice is safe. Reading from a closed file raises ValueError, not OSError. This error often means a file object has outlived the block of code that was supposed to use it.
Forgetting to close
If you never call close(), CPython closes the file when the last reference to the object disappears, and it may emit a ResourceWarning. You should not rely on this. Other Python implementations close files later or at unpredictable times. Even in CPython, a reference kept in a list or an exception traceback can keep the file open far longer than you expect. Writers are most at risk, because unflushed data can be lost. The next chapter shows the standard fix.
When open() fails
open() either returns a working file object or raises an exception. There is no half-open state. In particular, you never get a file object for a path that does not exist when reading:
try:
f = open("no_such_file.txt", encoding="utf-8")
except FileNotFoundError as err:
print("open failed:", err.filename)Because the exception happens inside open(), the name f is never assigned. If you later call f.close() in a cleanup block, that raises NameError. The with statement avoids this problem.
One side effect of a successful open() can surprise you. Opening a file for writing with "w" empties it immediately, at the moment of the open() call, not at the first write():
with open("keep.txt", "w", encoding="utf-8") as f:
f.write("important\n")
open("keep.txt", "w", encoding="utf-8").close()
with open("keep.txt", encoding="utf-8") as f:
print(repr(f.read()))This prints ''. The middle line opened the file and closed it without writing anything, and the old contents were gone. The with statement used here is the subject of the third chapter.
Always pass an encoding
For text files, open() uses a default encoding that depends on the operating system and its settings when you do not pass encoding=. A file that reads correctly on your Linux machine can fail or produce wrong characters on a Windows machine. Passing encoding="utf-8" explicitly, as every example here does, makes the behavior the same everywhere. A later chapter covers encodings and newlines in detail.
Summary of the model
open()returns a file object, not the file's contents.- A text file object is a stack:
TextIOWrapperover a buffered class overFileIO. - The mode string decides which class you get back, and the
bflag removes the text layer. - Writes are buffered, so the file on disk can lag behind your
write()calls untilflush()orclose(). - The object has a position and is its own iterator, so reading consumes it.
- A closed file raises
ValueErroron use. - File descriptors are limited, so files that are no longer needed should be closed.
Exercise
A script runs f = open("log.txt", "w", encoding="utf-8"), then f.write("started\n"), and then waits for ten minutes before closing the file. A second program reads log.txt after five minutes and sees an empty file. Give the cause, and name one call the first script can add right after the write so the second program sees the text.
Show answer
The text is still in the buffers of the file object. The TextIOWrapper and BufferedWriter layers hold small writes in memory until the buffer fills, the file is flushed, or the file is closed. Adding f.flush() after the write sends the data to the operating system, so the second program can read it.
Exercise
What does this code print, and why? f = open("data.txt", encoding="utf-8") first = f.read() second = f.read() print(len(first) > 0, second == "") f.close() Assume data.txt exists and contains at least one character.
Show answer
It prints True True. The first read() returns the whole file and moves the position to the end. The second read() starts at the end, so it returns an empty string.