Skip to content

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.

Beginner 10 min read·Lesson 196 of 306 in Python Programming

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

Python
with open("data.txt", encoding="utf-8") as f:
for line in f:
line = line.rstrip("\n")
...
  • read() for small files.
  • Iterate for large files.
  • Remove line endings before using lines.

Code examples

readline, readlines and read

Python
with open("poem.txt", "w", encoding="utf-8") as f:
f.write("roses are red\nviolets are blue\nsugar is sweet\n")
with open("poem.txt", encoding="utf-8") as f:
print(repr(f.readline()))
print(f.readlines())
with open("poem.txt", encoding="utf-8") as f:
print(len(f.read()))
Output
'roses are red\n'
['violets are blue\n', 'sugar is sweet\n']
46

Summing numbers line by line

Python
with open("nums.txt", "w", encoding="utf-8") as f:
f.write("10\n20\n30\n")
total = 0
with open("nums.txt", encoding="utf-8") as f:
for line in f:
total += int(line)
print(total)
Output
60

More examples

Analysing a log file

Python
from collections import Counter
log = "INFO start\nWARN disk 80%\nINFO request\nERROR timeout\nINFO request\nERROR disk full\n"
with open("app.log", "w", encoding="utf-8") as f:
f.write(log)
with open("app.log", encoding="utf-8") as f:
counts = Counter(line.split()[0] for line in f if line.strip())
print(dict(counts))
with open("app.log", encoding="utf-8") as f:
errors = [line.rstrip("\n") for line in f if line.startswith("ERROR")]
print(errors)
Output
{'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:

TextOutput
{'INFO': 3, 'WARN': 1, 'ERROR': 2}
['ERROR timeout', 'ERROR disk full']

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

data = f.read()
lines = f.readlines() # [] — already at the end

Prefer

data = f.read()
lines = data.splitlines()

After read(), the position is at the end of the file.

Comparing lines with newlines

Avoid

if line == "done":

Prefer

if line.rstrip("\n") == "done":

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

  1. 1
    Count the lines, words and characters of a text file (like the wc command).
  2. 2
    Print 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?
Practise this topic