PythonMastery
Python programs · Files · beginner

Read a file line by line in Python

Loop over a file object to read one line at a time, remove the new line with strip(), and number the lines with enumerate().

A file object is iterable: a for loop over it gives you one line at a time. Python does not load the whole file into memory, so this works for files of any size.

The program

python
with open("tasks.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\nCall Grace\n\nFinish report\n")

with open("tasks.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        line = line.strip()
        if not line:
            continue  # skip empty lines
        print(f"{number}. {line}")
output
1. Buy milk
2. Call Grace
4. Finish report

How it works

All lines as a list

If the file is small and you want a list of lines, .read().splitlines() gives you the lines without the \n characters:

python
with open("tasks.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\nCall Grace\nFinish report\n")

with open("tasks.txt", encoding="utf-8") as f:
    lines = f.read().splitlines()

print(lines)
output
['Buy milk', 'Call Grace', 'Finish report']

Related programs: Read a file.

Learn the idea: Files: Reading and Writing to Disk, File I/O, Pathlib, and Large Files, Loops: for, while, and the Pythonic Patterns

A longer explanation: How do I read a file line by line in Python?