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.
Mercury
Venus
Earthwith open("planets.txt") as file:
for line in file:
print(line)
Mercury
Venus
EarthWhere 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.
>>> "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:
4200
8100
6300total = 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)
Day 1: 4200 steps
Day 2: 8100 steps
Day 3: 6300 steps
Average: 6200.0int 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.