Python by Projects

unit

SAVE POINT

A game that forgets everything when you close it is no fun. Let's teach our program to WRITE the player's progress to a file and LOAD it back next time.

Each idea comes as a short ladder — simplest first, then one step up, then the real save system — with a Notice naming the one new thing.

You will learn

  • Write text to a file with with open(name, "w") as f: and f.write(...).
  • Read a whole file with f.read(), or one line at a time with for line in f:.
  • Rebuild a list of scores from a save file.
  • Recognize the error when a program loads a file that was never saved.

Lesson 1: Write a Save File

with open("savegame.txt", "w") as f: opens a file for writing and, when the block ends, closes it for you. f.write(...) puts text in the file. \n is the invisible newline that ends a line.

with open("savegame.txt", "w") as f:
    f.write("1200\n")
print("Saved one score.")

Output

Saved one score.

Notice

The with block opens savegame.txt for writing and closes it automatically when the block ends.

scores = [1200, 850, 990, 1430, 760]
with open("savegame.txt", "w") as f:
    for score in scores:
        f.write(str(score) + "\n")
print(f"Saved {len(scores)} scores.")

Output

Saved 5 scores.

Notice

A loop writes several lines — one score per line (str(...) because a file holds TEXT).

settings = {"volume": 8, "difficulty": "easy"}
with open("settings.txt", "w") as f:
    f.write("Ada\n")
    f.write(str(settings["volume"]) + "\n")
    f.write(settings["difficulty"] + "\n")
print("Saved the settings.")

Output

Saved the settings.

Notice

A different file can hold mixed lines — a name, a number, and a word — for the player's settings.

Try it yourself

n = int(input("How many scores? "))
scores = []
for i in range(n):
    scores.append(int(input(f"Score {i + 1}? ")))

with open("savegame.txt", "w") as f:
    for score in scores:
        f.write(str(score) + "\n")
print(f"Saved {len(scores)} scores.")

Notice

(It reads live input, so it does not run here.)

Lesson 2: Read a Save File

with open("savegame.txt") as f: (no "w") opens a file for reading. f.read() brings the whole file in as one text string.

with open("savegame.txt") as f:
    content = f.read()
print(content)

Output

1200
850
990
1430
760

Notice

f.read() returns the entire file as one string — exactly what was saved.

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

Output

1200

850

990

1430

760

Notice

One step up — for line in f: walks the file one LINE at a time (each line still carries its \n, so the output looks double-spaced).

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

Output

1200
850
990
1430
760

Notice

.strip() removes the trailing newline, so each line prints cleanly.

lines = []
with open("savegame.txt") as f:
    for line in f:
        lines.append(line.strip())
print(lines)

Output

['1200', '850', '990', '1430', '760']

Notice

One step up — .append() collects the cleaned lines into a LIST (still text for now).

loaded = []
with open("savegame.txt") as f:
    for line in f:
        loaded.append(int(line.strip()))
print(loaded)

Output

[1200, 850, 990, 1430, 760]

Notice

The one new step is int(...) — turn each line into a number so the list holds integers.

Lesson 3: Load the Save Point

Put it together: package the line-by-line loader into a helper. filename says which file to read; return sends the rebuilt list back.

def load_scores(filename):
    result = []
    with open(filename) as f:
        for line in f:
            result.append(int(line.strip()))
    return result


loaded = load_scores("savegame.txt")
print(f"Loaded {len(loaded)} scores")

Output

Loaded 5 scores

Real version: This already reads real input — it loads a save file; no separate input() version.

Put it together: the settings file has words as well as a number, so read it as text and use in to search it for the player's name.

with open("settings.txt") as f:
    info = f.read()

if "Ada" in info:
    print("Welcome back, Ada!")

Output

Welcome back, Ada!

Real version: This already reads real input — it loads a save file; no separate input() version.

What if a game loads a file that was never saved? Study the next cell, but do not run it.

Read the error

with open("missing.txt") as f:
    f.read()
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

FileNotFoundError tells us the program tried to load a file that does not exist yet. The safe plan: save first, then load.

Recap

  • Opening a file with "w" writes it, and the with block closes it for you.
  • \n ends a line, so each saved score gets its own line.
  • f.read() gives the whole file as one string; for line in f: gives one line per trip.
  • .strip() removes the newline, and int() turns each line back into a number.
  • A FileNotFoundError means the file does not exist yet: save first, then load.

You can now make a game remember its scores between runs.

Go to the exercises (25)

For parents and teachers: report a problem