Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I read a text file one line at a time in Python?

Quick answer

Open the file and loop over it with for line in file: to handle its lines one at a time. A line read from a text file normally still includes its newline. If you need to remove that ending while preserving spaces, use line.rstrip("\n"). By contrast, read() returns the entire file contents as one string. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

What’s the simplest way to read a local text file line by line in Python?

Geez

Use a with statement and loop over the open file. Replace sample.txt with the path to your file. This example assumes it contains a few lines of ordinary text:

with open("sample.txt", "r") as file:
    for line in file:
        print(line, end="")

The loop handles a line on each pass. A line read from a text file normally still has its newline character, and in text mode Python translates platform-specific line endings to \n. [S1] The end="" argument prevents print from adding another newline when the line already has one.

Follow-up question

How do I get each line without the newline, but keep spaces that might matter?

Geez

Remove only newline characters at the end with rstrip("\n"):

with open("sample.txt", "r") as file:
    for line in file:
        text = line.rstrip("\n")
        print(repr(text))

If a line contains hello followed by a newline, text remains hello , including its spaces. Avoid plain strip() when those spaces matter, because it removes surrounding whitespace too. Text mode translates platform-specific line endings to \n, so removing that ending does not require removing arbitrary whitespace. [S1] repr makes spaces easier to see in this demonstration; omit it if you do not need that view.

Follow-up question

What does line by line mean compared with calling read()?

Geez

A loop lets you handle lines as they are read. By contrast, read() returns the entire file contents as one string. [S1] For a small file, either approach may suit your task; the loop is useful when your code should work with separate lines rather than one string containing all the contents.

For example, assume sample.txt contains red, blue, and green, each on its own line:

with open("sample.txt", "r") as file:
    for line in file:
        color = line.rstrip("\n")
        print(f"Color: {color}")

The output is:

Color: red
Color: blue
Color: green

This shows the pattern; it does not establish a memory limit or guarantee a speed improvement for a particular file or program.

Follow-up question

Can you give me a compact version I can adapt, and a couple of things to check if the output looks wrong?

Geez

Change the filename and put your processing inside the loop:

with open("sample.txt", "r") as file:
    for line in file:
        text = line.rstrip("\n")
        # Do something with text, such as print(text)

If output seems to have blank lines, check whether the line already includes its ending before printing: print(line) can add another newline, while print(line, end="") does not add one. If spaces seem to disappear, check that you used rstrip("\n") rather than strip(). The documented behavior covers newline handling in text mode, but it cannot tell you what is in your particular file. Inspect a small sample if you need to check its contents. [S1]

A practical checklist

  • Replace sample.txt with the path to your file.

  • Open the file and loop with for line in file:.

  • Use line.rstrip("\n") when you need text without its newline.

  • Avoid strip() if leading or trailing spaces must be preserved.

  • Use print(line, end="") when the line already includes a newline and you want to avoid adding another.

A few more useful answers

Does each line still include its newline?

Normally, yes: a line read from a text file retains its newline. In text mode, platform-specific line endings are translated to \n. [S1]

What is the difference between `readline()` and `read()`?

readline() reads one line and normally leaves its newline at the end. read() returns the entire file contents as one string. [S1]

Does reading line by line guarantee lower memory use?

The documented distinction is that read() returns the whole file as one string, whereas readline() reads one line. That alone does not establish memory use or performance for a particular program. [S1]

Sources

References used for this guide.

  1. [S1] Python Tutorial: Reading and writing files
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work