Sub topic 1
What open() returns
Prerequisites
This chapter assumes you know basic Python syntax (variables, functions, loops), the difference between str and bytes, and how try/except works. You do not need any prior experience with files.
The file object
Calling open() does not read anything. It asks the operating system to open the file and returns a file object, which is a Python object that wraps the open file and gives you methods for reading and writing it.
f = open("notes.txt", "w", encoding="utf-8")
print(type(f))
print(f.name, f.mode, f.encoding, f.closed)
f.close()
print(f.closed)The output on a typical system is:
<class '_io.TextIOWrapper'>
notes.txt w utf-8 False
TrueThe attributes tell you how the object was opened. name is the path you passed, mode is the mode string, encoding is the text encoding, and closed reports whether the file has been closed.
What the object holds
A file object stands for a connection to a file. It holds three things:
- A handle from the operating system, called a file descriptor. This is a small integer the OS uses to identify the open file. The OS limits how many a process can have open at once.
- A buffer, which is a block of memory where Python collects data before passing it on. Writes often stay in the buffer and reach the disk later.
- A position, which is the offset in the file where the next read or write happens. It starts at 0 and moves forward as you read or write.
Because of the buffer, text you write may not be on disk until you call flush() or close(). Closing a file flushes the buffer and releases the descriptor.
Text objects and binary objects
The type of the returned object depends on the mode. In text mode, open() returns a TextIOWrapper. It converts between str and bytes using the encoding you give it. In binary mode (a mode with b), you get a BufferedReader or BufferedWriter, which work with bytes directly and do no decoding.
with open("notes.txt", encoding="utf-8") as text_file:
print(type(text_file).__name__)
print(type(text_file.read()).__name__)
with open("notes.txt", "rb") as binary_file:
print(type(binary_file).__name__)
print(type(binary_file.read()).__name__)For a file that exists, this prints:
TextIOWrapper
str
BufferedReader
bytesThe next chapters cover modes in detail. For now, remember that the mode decides whether you work with str or bytes.
Errors can happen at open time
Because open() talks to the operating system, it can fail before it returns anything. A missing file raises FileNotFoundError, and a file you may not access raises PermissionError. If open() raises, no file object exists, so there is nothing to close.
try:
f = open("missing.txt", encoding="utf-8")
except FileNotFoundError:
print("no such file")Closing the file
A file object you open yourself must be closed. If you forget, the descriptor stays in use and buffered data may be lost if the program ends abnormally. If an error occurs between open() and close(), the close() call is skipped. The with statement solves this by closing the file for you, even when an exception is raised. The next chapters cover it.
Exercise
You run f = open("data.bin", "rb") and then f.read(). What type does f.read() return, and what is the type of f's class family (text wrapper or buffered)?
Show answer
f.read() returns bytes. Because the mode contains b, f is a buffered binary object (a BufferedReader), not a TextIOWrapper, so no decoding takes place.
Exercise
A program writes a line with f.write("done\n") and then crashes before it calls f.close(). Why might the line be missing from the file?
Show answer
The text may still be in the file object's buffer and not yet written to disk. Calling flush() or close() (or using a with block) writes the buffer out.