Reading Files
Files allow programs to store and retrieve data permanently. Reading files is essential for processing data that exists outside your program — text files, CSV data, configuration files, and more.
Learning Objectives
- 11.4.1.1 Read data from text files
Conceptual Anchor
The Filing Cabinet Analogy
A file is like a document in a filing cabinet. To read it: (1)
open the drawer (open the file), (2) read the document (read
the contents), (3) close the drawer (close the file). The with
statement automatically closes it for you — like a self-closing drawer.
Rules & Theory
Opening and Reading Files
# Method 1: read() — entire file as one string
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Method 2: readline() — one line at a time
with open("data.txt", "r") as file:
line1 = file.readline() # First line
line2 = file.readline() # Second line
print(line1.strip()) # .strip() removes trailing \n
print(line2.strip())
# Method 3: readlines() — all lines as a list
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines) # ['line1\n', 'line2\n', 'line3\n']
# Method 4: Iterate line by line (BEST for large files)
with open("data.txt", "r") as file:
for line in file:
print(line.strip())File Open Modes
| Mode | Description | File must exist? |
|---|---|---|
"r" |
Read (default) | Yes |
"w" |
Write (overwrites!) | No (creates new) |
"a" |
Append (adds to end) | No (creates new) |
"r+" |
Read + Write | Yes |
The
with Statement
# WITHOUT with — manual close (error-prone)
file = open("data.txt", "r")
content = file.read()
file.close() # Easy to forget! Resource leak!
# WITH statement — automatic close (recommended!)
with open("data.txt", "r") as file:
content = file.read()
# File automatically closed here, even if an error occurs Always Use with
The with statement guarantees the file is closed properly, even if an error occurs.
Never use open() without with unless you have a specific reason.
Worked Examples
1 Reading and Processing a CSV
# File: students.txt
# Ali,16,95
# Dana,15,88
# Marat,16,72
with open("students.txt", "r") as file:
for line in file:
parts = line.strip().split(",")
name = parts[0]
age = int(parts[1])
score = int(parts[2])
print(f"{name} (age {age}): {score}%")2 Counting Lines, Words, Characters
with open("story.txt", "r") as file:
lines = file.readlines()
line_count = len(lines)
word_count = sum(len(line.split()) for line in lines)
char_count = sum(len(line.strip()) for line in lines)
print(f"Lines: {line_count}")
print(f"Words: {word_count}")
print(f"Characters: {char_count}")3 Finding Maximum Score
# File: scores.txt (one number per line)
# 78
# 95
# 62
# 88
with open("scores.txt", "r") as file:
scores = []
for line in file:
scores.append(int(line.strip()))
print(f"Highest: {max(scores)}")
print(f"Lowest: {min(scores)}")
print(f"Average: {sum(scores)/len(scores):.1f}")Pitfalls & Common Errors
FileNotFoundError
If the file doesn't exist, open("missing.txt", "r") raises
FileNotFoundError. Check the file path and name carefully.
Trailing Newlines
Each line includes \n at the end. Always use .strip() to remove it:
line.strip().
Data Type from Files is Always String
Everything read from a file is a string. Convert to int/float as needed:
int(line.strip()).
Pro-Tips for Exams
File Reading Tips
- Use
for line in file:for memory-efficient line-by-line reading - Use
.readlines()when you need to know total lines or access lines by index - Pattern:
line.strip().split(",")— strip whitespace, then split by delimiter - Always specify encoding for non-English text:
open("f.txt", "r", encoding="utf-8")
Graded Tasks
What are the 4 ways to read from a file? What does the with statement do?
Explain why .strip() is needed when reading lines from a file.
Write a program that reads numbers from a file (one per line) and prints their sum and average.
Read a CSV file with name, score pairs and find the student with the highest score.
Compare read() vs readlines() vs for line in file:.
When would you use each?
Build a word search tool: read a text file and let the user search for a word, displaying all lines containing it.
Self-Check Quiz
readline() return?with statement?