How to Read a File Line by Line in Python
If you want to process a text file one line at a time, Python gives you a simple and memory-friendly way to do it.
This is useful when working with:
- text files
- log files
- plain text data
- large files you do not want to load fully into memory
Quick answer
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
Use a for loop with open() to read one line at a time.strip() removes the newline at the end of each line.
What this task means
Reading a file line by line means Python gives you one line, then the next, then the next, until the file ends.
This is often better than reading the whole file at once because:
- it uses less memory
- the code is easy to read
- it works well for large files
If you are new to files, see Python file handling basics: read and write.
Recommended way: use open() with a for loop
This is the most common and beginner-friendly approach.
with open('example.txt', 'r') as file:
for line in file:
print(line)
How it works
open('example.txt', 'r')opens the file in read modewithmakes sure the file is closed automaticallyfor line in filereads one line at a time
Example file
Suppose example.txt contains:
apple
banana
cherry
Then this code:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
prints:
apple
banana
cherry
If you want to understand file opening in more detail, see the Python open() function explained.
Why lines include newline characters
Most text file lines end with a newline character, written as \n.
That means when Python reads a line, the newline is usually still there.
For example:
with open('example.txt', 'r') as file:
for line in file:
print(repr(line))
Possible output:
'apple\n'
'banana\n'
'cherry\n'
This matters because print() adds its own newline too. So if you do this:
with open('example.txt', 'r') as file:
for line in file:
print(line)
you may see extra blank lines between outputs.
To avoid that, remove the newline first:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
When to use strip() vs rstrip()
These methods remove characters from a string, but they do not behave the same way.
strip()
strip() removes whitespace from both ends of the line.
line = " hello\n"
print(line.strip())
Output:
hello
rstrip()
rstrip() removes whitespace only from the end.
line = " hello\n"
print(line.rstrip())
Output:
hello
rstrip('\n')
If you only want to remove the newline character, use:
line = " hello\n"
print(line.rstrip('\n'))
Output:
hello
Use:
strip()if you want to clean both endsrstrip()if leading spaces should stayrstrip('\n')if you only want to remove the line ending
Another option: readline() in a loop
You can also read one line at a time with readline().
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()
When this is useful
readline() can help when you want more manual control over reading.
But for most beginners, this is less clear than:
for line in file:
So in most cases, the for loop approach is the better choice.
If you want a broader overview of file reading methods, see how to read a file in Python.
Read line numbers with enumerate()
Sometimes you want both the line content and the line number.
Use enumerate() for that:
with open('example.txt', 'r') as file:
for line_number, line in enumerate(file, start=1):
print(f"Line {line_number}: {line.strip()}")
Output:
Line 1: apple
Line 2: banana
Line 3: cherry
This is useful for:
- debugging
- showing errors in a specific line
- displaying line numbers to the user
You can learn more in the Python enumerate() function explained.
Common errors and checks
A few common problems can stop file reading from working.
FileNotFoundError
This happens when the file path is wrong or the file does not exist.
with open('missing.txt', 'r') as file:
for line in file:
print(line)
To fix it:
- make sure the file name is correct
- check that the file is in the expected folder
- use the full path if needed
If you need help with this error, see how to fix FileNotFoundError: [Errno 2] No such file or directory.
PermissionError
This happens when Python does not have permission to open the file.
Possible causes:
- the file is protected
- the file is open in a restricted location
- your program does not have access rights
Check the current folder
If you use a relative path like 'example.txt', Python looks in the current working directory.
You can check it with:
import os
print(os.getcwd())
Check whether a file exists
import os
print(os.path.exists('example.txt'))
This returns True or False.
See also:
Make sure the file is opened in read mode
Use 'r' when reading:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
Common mistakes
These are some common causes of problems when reading a file line by line:
- Using the wrong file path
- Forgetting that each line usually ends with
\n - Using
read()when line-by-line reading is better - Trying to open a file that does not exist
- Printing raw lines and getting unexpected blank spacing
Helpful checks while debugging:
print(line)
print(repr(line))
import os; print(os.getcwd())
import os; print(os.path.exists('example.txt'))
repr(line) is especially useful because it shows hidden characters like \n.
FAQ
What is the easiest way to read a file line by line in Python?
Use with open(...) as file and loop with for line in file.
Why do I see extra blank lines when printing lines?
Each line often already ends with a newline character, and print() adds another one.
Should I use read() or readlines() instead?
Use a for loop over the file for most line-by-line tasks. It is simpler and uses less memory for large files.
How do I get line numbers too?
Use enumerate(file, start=1) inside the loop.