Python Arena
Step 2 of 5

Going through a file line by line

read() gives you the whole file at once. More often a program handles a file one line at a time, and a file handle makes that easy: it works in a for loop much like a list of strings. Each round, the loop variable gets the next line of the file.

The file planets.txt
Mercury
Venus
Earth
with open("planets.txt") as file:
    for line in file:
        print(line)
Output
Mercury

Venus

Earth

Where do the empty lines come from? Each line of a file ends with a line break, the character \n, and the line Python reads includes it: the first line is "Mercury\n". print then adds a line break of its own, so every line is followed by an empty one. (The very last line of a file may or may not end with \n, depending on how the file was saved.)

Removing the line break with strip

You have met the string method strip in the module on strings and lists. It returns a copy of a string without the whitespace at its start and end, and whitespace means line breaks and tabs as well as spaces. Spaces in the middle stay where they are. strip has two relatives: rstrip removes whitespace only from the right end of the string, and lstrip only from the left end.

In the Python interpreter
>>> "Venus\n".strip()
'Venus'
>>> "   New York  \n".strip()
'New York'
>>> len("Venus\n")
6
>>> len("Venus\n".strip())
5
>>> "  indented line\n".rstrip()
'  indented line'
>>> "  indented line\n".lstrip()
'indented line\n'

Like every string method, strip doesn't change the string it's called on (strings can't be changed). It returns a new string, so store the result: line = line.strip().

Why the line break matters

An empty line in the printout is the harmless case. Comparisons are worse: "Earth\n" == "Earth" is False, so a program that looks for the line Earth without stripping the lines never finds it, and the length of every line is one too many. Make strip a habit whenever you read lines from a file.

Lines that hold numbers are converted with int or float as usual. This file has the steps someone walked on each of three days:

The file steps.txt
4200
8100
6300
total = 0
days = 0
with open("steps.txt") as file:
    for line in file:
        steps = int(line.strip())
        days += 1
        total += steps
        print(f"Day {days}: {steps} steps")
print("Average:", total / days)
Output
Day 1: 4200 steps
Day 2: 8100 steps
Day 3: 6300 steps
Average: 6200.0

int would forgive the line break here (it ignores whitespace around a number), but stripping first keeps the habit the same for every line. A file can also end with an empty line; after strip it is the empty string "", which a program can skip with if line == "": continue.

Your task

Challenge 1 of 3

Fill in the blanks so the program greets each guest in the file guests.txt, one per line. With this file

Ada
Grace
Linus

the program prints:

Welcome, Ada!
Welcome, Grace!
Welcome, Linus!

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

The file rain.txt has one number on each line: how many millimeters of rain fell on one day. Write a program that reads the file and prints the number of days, the number of dry days (days with 0 mm) and the total rainfall.

With this file

0
5
12
0
4
0
2

the program prints:

Days: 7
Dry days: 3
Total: 23 mm