×

python · level 2 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Read a file all at once, or .

open("scores.txt") with no mode opens a file for reading. file.read() hands back everything in it as one string, newlines and all.

Loop over the file instead and you get it line by line: for line in file:. Each line still ends with its \n, so .strip() it before you use it, and convert numbers as usual.

Open a file that does not exist and you get a . Catch it with try whenever a file might not be there yet.

with open("scores.txt", "w") as file:
    file.write("12\n30\n8\n")
total = 0
with open("scores.txt") as file:
    for line in file:
        total = total + int(line.strip())
print(f"Total: {total}")

Each lesson writes its own file first, because every run starts in an empty folder.