How to read a file line by line in Python
· 1 min read · Updated March 16, 2026 · beginner
python files io
The most common way to read a file line by line is using a for loop directly on the file object:
with open("example.txt") as f:
for line in f:
print(line)
This is the Pythonic approach and works efficiently for large files because it iterates lazily — only one line is in memory at a time.
Using .readlines()
If you need a list of all lines upfront:
with open("example.txt") as f:
lines = f.readlines()
for line in lines:
print(line)
Be careful with this approach for large files — it loads everything into memory at once.
Using iter() with readline()
For more control over the iteration:
with open("example.txt") as f:
for line in iter(f.readline, ""):
process(line)
This stops when readline() returns an empty string (end of file).
Stripping newlines
Each line includes the trailing newline character. Remove it with strip():
with open("example.txt") as f:
for line in f:
print(line.strip())