How to Read a Text File Line by Line in Python
Reads a text file line by line with an enumerated for loop and prints each line number and content.
Python code
12 linesfrom pathlib import Path
def read_lines(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
for line_number, line in enumerate(file, start=1):
print(f"Line {line_number}: {line.rstrip()}")
if __name__ == "__main__":
sample_file = Path("sample.txt")
sample_file.write_text("First line\nSecond line\nThird line\n", encoding='utf-8')
read_lines(sample_file)
sample_file.unlink()
Output
Line 1: First line
Line 2: Second line
Line 3: Third line
How it works
Using with open(...) ensures the file is closed automatically even if an error occurs. The for line_number, line in enumerate(file, start=1) iterates over each line lazily, so memory usage stays constant for large files. line.rstrip() removes trailing newline characters, giving clean output. The Path object from pathlib provides a convenient way to create and delete the sample file.
Common mistakes
- Forgetting to specify encoding='utf-8' when the file has non-ASCII characters
- Trying to read a file after it has been closed outside the with block
- Using `readlines()` for huge files, which loads everything into memory at once
Variations
- Use `file.readline()` in a while loop if you need manual control over when to stop.
- Use `with open(file_path) as f: for line in f:` to iterate without numbering.
Real-world use cases
- Processing large log files line by line without exceeding memory limits.
- Reading configuration files where each line defines a setting or parameter.
- Parsing CSV-like data from plain text files for batch import into a database.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.