Sub topic 4
Reading Text Files
This chapter covers the methods a text-mode file object gives you for reading: read(), readline(), readlines(), and iteration. It also covers how to choose between them, and the errors people commonly hit.
Prerequisites
This chapter assumes you know the following:
- You can write a basic Python program with variables, functions, and loops.
- You know that
strholds text andbytesholds raw data. - You can use
try/except. - You have seen
open()and thewithstatement. The previous chapters cover them.
Every example opens files in text mode, the default. In text mode Python decodes bytes into str using an encoding, and it translates line endings. Both steps affect what you read, so every example names its encoding explicitly.
The sample file
The examples below use one small file. Its last line has no trailing newline, and it contains one blank line. Both details matter for the edge cases.
from pathlib import Path
Path("sample.txt").write_text("alpha\n\nbeta\ngamma", encoding="utf-8")The file's content is the 17-character string alpha\n\nbeta\ngamma.
Five ways to read
Reading everything with read()
read() with no argument returns the rest of the file as one string.
with open("sample.txt", encoding="utf-8") as f:
print(repr(f.read()))This prints 'alpha\n\nbeta\ngamma'. It is the simplest option. The whole file must fit in memory, and the decoded str can take more space than the file does on disk. For a multi-gigabyte log, prefer one of the approaches below.
Iterating over lines
A file object is an iterator that yields one line at a time, including the trailing "\n". Python reads the file in buffered blocks behind the scenes, so memory use stays small whatever the file size.
with open("sample.txt", encoding="utf-8") as f:
for line in f:
print(repr(line))The output is:
'alpha\n'
'\n'
'beta\n'
'gamma'Two details to notice:
- The blank line is
'\n', not''. - The last line has no
"\n"because the file does not end with one.
If you print each line without stripping it, print adds its own newline and the output looks double-spaced. Use line.rstrip("\n") to remove only the newline. A bare line.strip() also removes leading and trailing spaces and tabs, which may be data you want to keep.
Reading one line with readline()
readline() returns the next line, or an empty string at the end of the file. Use it when you need to pull out a header and then handle the rest differently.
with open("sample.txt", encoding="utf-8") as f:
header = f.readline().rstrip("\n")
body = f.read()
print(repr(header))
print(repr(body))This prints 'alpha' and '\nbeta\ngamma'.
The end-of-file test must be line == "", not not line.strip(). A blank line in the middle of a file is "\n", which is not empty. A loop that stops on "falsy after stripping" quits at the first blank line.
with open("sample.txt", encoding="utf-8") as f:
while True:
line = f.readline()
if line == "":
break
print(repr(line))This loop prints the same four lines as the for loop. In ordinary code the for loop is clearer, so keep readline() for cases where you control the reading step by step.
Loading all lines with readlines()
readlines() returns a list of lines with their newlines attached.
with open("sample.txt", encoding="utf-8") as f:
print(f.readlines())The result is ['alpha\n', '\n', 'beta\n', 'gamma']. It has the same memory cost as read(), plus the overhead of a list. It is useful when you need random access to lines or the line count up front. If you want lines without newlines, use splitlines() on the string:
with open("sample.txt", encoding="utf-8") as f:
print(f.read().splitlines())The result is ['alpha', '', 'beta', 'gamma']. Be aware that str.splitlines() splits on more boundaries than "\n". These include \x0b, \x0c, and \u2028. A file that contains one of these characters inside a line gives you more items than iterating the file would.
Reading a fixed amount with read(size)
In text mode, read(n) returns up to n characters, not bytes. Each call continues where the previous one stopped.
with open("sample.txt", encoding="utf-8") as f:
print(repr(f.read(3)))
print(repr(f.read(3)))
print(repr(f.read()))This prints 'alp', then 'ha\n', then '\nbeta\ngamma'.
This is how you process a file with no meaningful line structure, such as a single huge line of minified text. A generator keeps the chunking logic in one place:
def read_chunks(path, size=4096):
with open(path, encoding="utf-8") as f:
while chunk := f.read(size):
yield chunk
total = sum(len(chunk) for chunk in read_chunks("sample.txt", size=5))
print(total)This prints 17. The loop ends when read() returns "".
Choosing a method
| Method | Returns | Memory use | Best for |
|---|---|---|---|
| `f.read()` | one `str` | whole file | small files, parsing a whole document |
| `for line in f` | one line per step | one line | line-oriented processing of any size |
| `f.readline()` | one line | one line | reading a header, manual control |
| `f.readlines()` | list of lines | whole file plus list | indexing lines, counting lines |
| `f.read(n)` | up to `n` characters | `n` characters | files without line structure, very long lines |
Newlines and decoding on read
Universal newlines
When you open a file in text mode without a newline argument, Python translates "\r\n" (Windows) and "\r" (old Mac) to "\n" as it reads. Your code only ever sees "\n".
from pathlib import Path
Path("windows.txt").write_bytes(b"a\r\nb\r\n")
with open("windows.txt", encoding="utf-8") as f:
print(repr(f.read()))
with open("windows.txt", encoding="utf-8", newline="") as f:
print(repr(f.read()))The first read prints 'a\nb\n'. The second prints 'a\r\nb\r\n'. Passing newline="" turns the translation off and leaves the line endings exactly as stored. The csv module requires this setting.
Decoding errors
If the bytes in the file are not valid in the chosen encoding, Python raises UnicodeDecodeError. Here the file holds Latin-1 text but is read as UTF-8:
from pathlib import Path
Path("latin.txt").write_bytes(b"caf\xe9\n")
try:
with open("latin.txt", encoding="utf-8") as f:
f.read()
except UnicodeDecodeError as exc:
print(exc.reason)
with open("latin.txt", encoding="latin-1") as f:
print(repr(f.read()))
with open("latin.txt", encoding="utf-8", errors="replace") as f:
print(repr(f.read()))The three results are:
- The message
invalid continuation byte. 'café\n', which is correct because the file really is Latin-1.- A string where the bad byte became the replacement character
U+FFFD.
errors="replace" stops the exception but loses data silently. Use it for display or best-effort scanning, not for text you plan to write back. The right fix is almost always to find out the real encoding.
Common errors
- Reading twice. After
read()the position is at the end of the file, so a secondread()returns"". This is a frequent cause of "my file is empty" bugs.
``python with open("sample.txt", encoding="utf-8") as f: first = f.read() second = f.read() print(len(first), repr(second)) ``
This prints 17 ''. A later chapter covers seek(), which moves the position back.
- Using
read()on a huge file. It either exhausts memory or runs very slowly. Iterate instead.
- Forgetting the encoding.
open("x.txt")withoutencodinguses a locale-dependent default. On many Windows systems this is not UTF-8. A script that works on your laptop can fail on a colleague's machine.
- Processing lines that still end with
"\n". Comparisons such asline == "ERROR"fail because the line is"ERROR\n". Strip the newline before comparing.
- Calling
tell()inside afor line in floop. For text files this raisesOSError: telling position disabled by next() call. Usereadline()in awhileloop if you need positions while reading.
- Keeping the data after the file closes. The
forloop yields strings, which remain valid after thewithblock ends. Trying to read fromfitself after the block raisesValueError: I/O operation on closed file.
A worked example: scanning a log
The task is to find the line numbers and text of every error in a log file. This is line-oriented work, so the program iterates over the file. It uses enumerate to count lines starting from 1.
from pathlib import Path
Path("app.log").write_text(
"INFO start\nERROR disk full\nINFO retry\nERROR timeout\n",
encoding="utf-8",
)
errors = []
with open("app.log", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
if line.startswith("ERROR"):
errors.append((number, line.rstrip("\n")))
print(errors)The output is [(2, 'ERROR disk full'), (4, 'ERROR timeout')]. Memory use stays flat whether the log has four lines or four hundred million. The result list holds only the matching lines. If even that could be too large, replace the list with a generator or write the matches to another file as you go.
Summary
- Iterate with
for line in ffor line-based work. It is the default choice and scales to any file size. - Use
read()orreadlines()only when the file is known to be small. - Use
readline()for step-by-step control and test for""at the end of the file. - Use
read(n)in a loop for files that are not organized in lines. - Lines keep their
"\n", and the last line of a file may not have one. - Always name the encoding, and expect
UnicodeDecodeErrorwhen the guess is wrong.
Exercise
A loop reads a file with while True: line = f.readline(); if not line.strip(): break. It stops early on a file that has a blank line in the middle. Why, and how do you fix it?
Show answer
A blank line in the middle of a file is read as "\n". After strip() it becomes "", so not line.strip() is true and the loop breaks before the end of the file. Only the end of the file makes readline() return "" with no newline. Fix the test to if line == "": break, or replace the loop with for line in f:.
Exercise
Write a function count_lines(path) that returns the number of lines in a UTF-8 text file without loading the whole file into memory. What does it return for the sample file alpha\n\nbeta\ngamma?
Show answer
def countlines(path): with open(path, encoding="utf-8") as f: return sum(1 for in f) For the sample file it returns 4. The blank line counts as a line, and the final line "gamma" counts even though it has no trailing newline.