How to Read File Line by Line in Python: Simple Guide
To read a file line by line in Python, use a
with open(filename) as file block and loop over the file object with for line in file. This reads each line one at a time, which is memory efficient and easy to use.Syntax
Use with open(filename) as file to open the file safely. Then use for line in file to read each line one by one. The line variable holds the current line as a string.
- with open(filename) as file: Opens the file and ensures it closes automatically.
- for line in file: Loops through each line in the file.
- line: The current line read from the file, including the newline character.
python
with open('example.txt', 'r') as file: for line in file: print(line)
Example
This example reads a file named example.txt line by line and prints each line. It shows how to handle the newline characters by using line.strip() to remove extra spaces and newlines.
python
with open('example.txt', 'r') as file: for line in file: print(line.strip())
Output
Hello, world!
This is line 2.
Last line here.
Common Pitfalls
One common mistake is forgetting to close the file, which can cause errors or resource leaks. Using with open() handles this automatically. Another issue is not handling newline characters, which can cause extra blank lines when printing.
Also, reading the whole file at once with read() or readlines() can use a lot of memory for big files.
python
# wrong way: file = open('example.txt', 'r') lines = file.readlines() for line in lines: print(line) file.close() # right way: with open('example.txt', 'r') as file: for line in file: print(line.strip())
Quick Reference
| Action | Code Example |
|---|---|
| Open file safely | with open('file.txt', 'r') as file: |
| Read line by line | for line in file: |
| Remove newline | line.strip() |
| Print line | print(line) |
Key Takeaways
Use 'with open(filename) as file' to open files safely and automatically close them.
Loop over the file object with 'for line in file' to read lines one by one efficiently.
Use 'line.strip()' to remove extra spaces and newline characters from each line.
Avoid reading the entire file at once for large files to save memory.
Closing files manually is error-prone; prefer the 'with' statement.