Module 13 · File Handling — topic 3 of 15
Reading
Reading text files: read() for the whole file, readline() and readlines(), iterating line by line for large files, stripping line endings, and processing file contents.
Learning objectives
- Use read, readline and readlines
- Iterate over a file line by line
- Process lines correctly including line endings
Definition
Reading means getting data from an opened file. read() returns the whole content (or n characters), readline() returns one line, readlines() returns a list of lines, and iterating over the file object yields lines one at a time.
Introduction
Once a file is open, you need its contents: all at once for a small settings file, or line by line for a large log.
Why it matters
Choosing the right reading method keeps memory use low for big files and makes processing code simple.
Detailed explanation
f.read() returns the entire remaining content as one string. f.read(n) returns up to n characters. At the end of the file it returns an empty string.
f.readline() returns the next line including its "\n", or "" at the end of the file.
f.readlines() returns a list of all remaining lines, each with its "\n".
for line in f: reads one line at a time. It is memory-efficient and the most common way to process text files.
The file object remembers a position. After reading, the next read continues where the last one stopped; reopen the file (or use f.seek(0)) to start over.
Lines keep their line endings. Use line.rstrip("\n") or line.strip() before comparing or splitting, and str.splitlines() on whole-file text.
int() and float() ignore surrounding whitespace, so int(line) works even with a trailing newline.
Syntax
- read() for small files.
- Iterate for large files.
- Remove line endings before using lines.
Code examples
readline, readlines and read
'roses are red\n' ['violets are blue\n', 'sugar is sweet\n'] 46
Summing numbers line by line
60
More examples
Analysing a log file
{'INFO': 3, 'WARN': 1, 'ERROR': 2}
['ERROR timeout', 'ERROR disk full']Step-by-step explanation
- The generator expression reads the file lazily, one line at a time.
- The first word of each line is its level; Counter tallies them.
- The file is opened again for the second pass because the first pass left the position at the end.
Expected output
Running “Analysing a log file” prints exactly:
Practical applications
- Log analysis and monitoring scripts.
- Reading word lists, configuration and data files.
Best practices
- Iterate line by line for large files.
- Strip line endings before using lines.
- Read once and reuse the data when you need it several times.
Common mistakes
Reading twice from the same position
Avoid
Prefer
After read(), the position is at the end of the file.
Comparing lines with newlines
Avoid
Prefer
Each line still contains "\n".
Important notes
- f.read() on a multi-gigabyte file loads all of it into memory; iterate instead.
Key takeaways
- read(), readline(), readlines() and iteration read text.
- Lines keep their "\n".
- The file position moves forward as you read.
Try it yourself
- 1Count the lines, words and characters of a text file (like the wc command).
- 2Print only the lines of a file that contain a given word, with their line numbers.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?