🎓 A1Learner
🔍
0 of 52 lessons completed

Python Reading Files Line by Line

Reading line by line takes one line at a time. A for loop over the file does the job.

Loop over the lines

The loop prints each line. strip() drops the newline.

with open("shopping.txt", "w") as f:
    f.write("Milk\nBread\nEggs\n")

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

Skip the blank lines

A blank line turns empty after strip(). The if check skips it.

with open("notes.txt", "w") as f:
    f.write("First line\n\nSecond line\n")

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

Count the lines

The loop can count as it reads. The count proves each line was seen.

with open("days.txt", "w") as f:
    f.write("Mon\nTue\nWed\nThu\n")

count = 0
with open("days.txt") as f:
    for line in f:
        count = count + 1
print(count)

Example

with open("diary.txt", "w") as f:
    f.write("Rain in the morning.\n\nWalked the dog.\nRead a book.\n")

number = 0
with open("diary.txt") as f:
    for line in f:
        line = line.strip()
        if line == "":
            continue
        number = number + 1
        print(number, line)
print("Lines:", number)

Key points

  • Line: one row of text in a file
  • Use for line in file to read each line in turn
  • Use line.strip() to drop the newline at the end
  • A blank line turns empty after strip()
  • Use if line == "" to skip a blank line
  • The with block closes the file at the end

In this example, the program writes a diary file first. It holds three notes and one blank line. The loop reads the file one line at a time. strip() drops each newline. The if check skips the blank line. Each real line gets a number as it prints. The last line prints the total count of three.

Note

read() loads the whole file at once, while the loop takes one line.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does for line in file do?