Sub topic 4
Reading Text Files
What this chapter assumes
You should already know how open() returns a file object, how the "r" mode works, and how a with block closes the file. You should also be comfortable with try/except and with the difference between str and bytes. This chapter covers the ways to get text out of a file once it is open.
The working model
A text-mode file object keeps a position, which is a marker for the next character to read. Every read method decodes text from that position and moves the marker forward. When the marker reaches the end of the file, reads return an empty string "". They do not raise an error.
The examples below use a notes.txt that contains three lines: first line, second line and third line.
| Method | Returns | Memory use |
|---|---|---|
| `f.read()` | The rest of the file as one string | Whole file |
| `f.read(n)` | Up to `n` characters | `n` characters |
| `f.readline()` | One line, including its `\n` | One line |
| `f.readlines()` | A list of all remaining lines | Whole file |
| `for line in f` | One line per loop pass | One line |
Reading everything at once
with open("notes.txt", encoding="utf-8") as f:
whole = f.read()
print(whole.splitlines())This is the simplest option and fine for small files. A large file has to fit in memory, because the result is a single string.
Reading line by line
Iterating over the file object is the usual way to process a file. Python reads and buffers the data in the background and hands you one line at a time.
with open("notes.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.rstrip("\n"))Each line still ends with "\n", except possibly the last line of the file. Use rstrip("\n") to remove only the newline. Plain strip() also removes leading and trailing spaces, which you may want to keep.
readline() is useful when you need to take one line at a time with other code in between, such as a header line followed by data.
with open("notes.txt", encoding="utf-8") as f:
header = f.readline()
rest = f.read()
print(repr(header))
print(repr(rest))Because the position carries over, read() here returns only the lines after the header.
Reading in chunks
For text with no useful line breaks, or when you want a fixed memory budget, pass a size to read(). The loop stops when read() returns an empty string.
with open("notes.txt", encoding="utf-8") as f:
while chunk := f.read(4096):
print(len(chunk))In text mode, the size counts characters, not bytes.
Choosing a method
Common errors
- Reading twice. A second
f.read()on the same open file returns"", because the position is already at the end. Store the first result in a variable, or reopen the file. - Reading after the block ends. Using
fafter thewithblock raisesValueError: I/O operation on closed file. Do all the reading inside the block. - Confusing a blank line with the end of the file.
readline()returns"\n"for a blank line and""only at the end. Testif not line:for the end, notif line == "\n":. - Leaving out
encoding. Without it, Python uses the platform default, so the same script can read a file correctly on one machine and fail or garble text on another. Name the encoding every time. - Surprise
FileNotFoundError. A relative path such as"notes.txt"is resolved against the current working directory, not the script's folder.
Exercise
A file has 3 lines. You run f.readline() three times and then a fourth time. What does the fourth call return, and what does it tell you?
Show answer
It returns the empty string "". That means the position is at the end of the file. A blank line in the middle of a file would return "\n" instead, so an empty string reliably signals the end.
Exercise
Write a loop that prints each line of notes.txt without its trailing newline and without loading the whole file into memory.
Show answer
with open("notes.txt", encoding="utf-8") as f: for line in f: print(line.rstrip("\n"))