Reading Files with
Context Managers
Master Python's open() function and the with statement to read files safely, cleanly, and without resource leaks.
What Is a File in Python?
A file is a named location on disk that stores data: text documents, CSV data, configuration settings, log output, and more. Python treats files as objects with methods for reading, writing, and closing.
The open() Function
Python's built-in open() function takes a filename (and optionally a mode) and returns a file object.
f = open("data.txt", "r") content = f.read() print(content) f.close()
The Problem with Manual Closing
If an error occurs between open() and close(), the close() line never runs. The file stays open, leaking a system resource.
f = open("data.txt", "r") content = f.read() result = 1 / 0 # ZeroDivisionError! f.close() # Never reached!
Enter the Context Manager
A context manager is a Python pattern that automatically sets up and tears down a resource. The with statement activates it.
with open("data.txt", "r") as f: content = f.read() print(content) # f.close() is called automatically here
The with Statement: Core Rule
Three Ways to Read
with open("data.txt") as f: all_text = f.read() # "line1\nline2\nline3\n" with open("data.txt") as f: first = f.readline() # "line1\n" with open("data.txt") as f: lines = f.readlines() # ["line1\n", "line2\n", ...]
Manual vs Context Manager
Iterating Over Lines
A file object is iterable: you can loop over it directly with a for loop. This is the most memory-efficient way to process a file line by line.
with open("scores.txt") as f: for line in f: line = line.strip() # remove \n print(line)
Step-by-Step Checklist
Example 1: Read Entire File
Read a greeting message from a file and display it.
# greeting.txt contains: # Hello, World! # Welcome to Python. with open("greeting.txt", "r") as f: message = f.read() print(message) # Output: # Hello, World! # Welcome to Python.
Example 2: Count Lines in a File
Count how many lines are in a text file using a for loop.
count = 0 with open("poem.txt") as f: for line in f: count += 1 print(f"Total lines: {count}")
Example 3: Parse Structured Data
Read a file where each line contains a name and score separated by a comma, and compute the average.
# scores.txt: # Alice,92 # Bob,85 # Carol,97 total = 0 count = 0 with open("scores.txt") as f: for line in f: name, score = line.strip().split(",") total += int(score) count += 1 avg = total / count print(f"Average: {avg}") # Average: 91.333...
Common Mistakes
Comparison Summary
| .read() | .readline() | .readlines() | for loop | |
|---|---|---|---|---|
| Returns | One string | One line | List of strings | One line/iteration |
| Memory | Loads all | Minimal | Loads all | Minimal |
| Best For | Small files | Header lines | Index access | Large files |
| Includes \n | Yes | Yes | Yes | Yes |
Question 1 of 5
What is the main advantage of using a with statement when opening a file?
Question 2 of 5
What does f.readlines() return?
Question 3 of 5
Consider the following Python code:
with open("notes.txt") as f:
data = f.read()
print(f.read())
What happens when the print(f.read()) line executes?
Question 4 of 5
You have a 10 GB log file. Which reading approach is most memory-efficient?
Question 5 of 5
Consider a file names.txt with the following content:
Alice
Bob
Carol
A student writes this code:
with open("names.txt") as f:
for line in f:
if line == "Bob":
print("Found Bob!")
The program never prints "Found Bob!" Why?