Skip to main content
Files

How to read a file line by line in Python

Quick answer

Iterate the file object directly: for line in f. Uses constant memory even on huge files.

with open("data.txt", encoding="utf-8") as f:
    for line in f:
        line = line.rstrip("\n")
        print(line)

A file object is its own iterator β€” for-looping it yields one line at a time, including the trailing newline. This is O(1) memory: even a 10GB file works because only one line is held in memory at once.

.rstrip('\n') trims the newline. Use plain .rstrip() to also strip trailing whitespace. Never use .strip() unless you actually want to lose leading whitespace too (breaks indented content).

Avoid f.readlines() β€” it loads the entire file into a list, which OOMs on large files. And avoid f.read().split('\n') β€” same problem plus a subtle bug: it produces an empty string for a trailing newline.

Variations

Skip blank lines

with open("data.txt", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        print(line)

Common when parsing config or CSV-like files.

First N lines only

from itertools import islice
with open("data.txt", encoding="utf-8") as f:
    for line in islice(f, 100):
        print(line, end="")

islice avoids reading the rest of the file.

Enumerate for line numbers

with open("data.txt", encoding="utf-8") as f:
    for i, line in enumerate(f, 1):
        print(f"{i}: {line}", end="")

start=1 gives 1-based numbering like most editors.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free β†’

Unlock every lesson

Pro β€” $12/mo, unlimited AI, cancel any time.

See Pro plans β†’

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos