Q&A library Python

How do I read a file line by line in Python?

Python Beginner context-managerfilesio

Short answer

Open the file in a with block and iterate over it directly, which reads one line at a time and is memory efficient. Strip the trailing newline from each line if you do not want it.

The short version

Open the file in a with block and loop over the file object directly. This yields one line at a time without loading the whole file into memory, so it works on files far larger than your RAM. Each line keeps its trailing newline, so call strip if you want it removed.

The idiomatic way

with open("notes.txt") as f:
    for line in f:
        print(line.strip())

Iterating the file object is the key: it reads lazily, line by line. The with block guarantees the file is closed afterwards, even if an error occurs partway through.

Why not read it all first

You will see this pattern:

with open("notes.txt") as f:
    lines = f.readlines()   # whole file into a list
for line in lines:
    print(line.strip())

It works, but readlines pulls the entire file into memory at once. On a small file that is fine; on a multi-gigabyte log it can exhaust memory. Prefer direct iteration unless you specifically need all lines in a list.

Stripping the newline

Each line includes its \n, so printing adds a blank line unless you strip. Use strip() to remove leading and trailing whitespace including the newline, or rstrip("\n") to remove only the newline and keep other spacing.

line.strip()        # remove all surrounding whitespace
line.rstrip("\n")   # remove only the trailing newline

Getting line numbers

Wrap the loop in enumerate rather than keeping a manual counter.

with open("notes.txt") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())

Encoding

For text files, state the encoding to avoid platform-dependent surprises, especially with non-English characters.

with open("notes.txt", encoding="utf-8") as f:
    ...

The habit to keep

Always open files in a with block. It ties the file's lifetime to the block, so you never leak an open file handle by forgetting to close it, which is a genuine problem in long-running programs.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project