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.

Easy Python 3.6+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

12 lines
Python 3.6+
from 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

stdout
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

  1. Use `file.readline()` in a while loop if you need manual control over when to stop.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.