Exit slides Esc

SAVE POINT

Slide 1 of 23

  1. 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.

    • 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.

  2. 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.

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

    Output

    Saved one score.
    

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

  4. 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.
    

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

  5. 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.
    

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

  6. Try it
    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.")

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

  7. 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.

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

    Output

    1200
    850
    990
    1430
    760
    
    

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

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

    Output

    1200
    
    850
    
    990
    
    1430
    
    760
    
    

    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).

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

    Output

    1200
    850
    990
    1430
    760
    

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

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

    Output

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

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

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

    Output

    [1200, 850, 990, 1430, 760]
    

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

  13. 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.

  14. 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
    
  15. Real version: This already reads real input — it loads a save file; no separate input() version.

  16. 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.

  17. with open("settings.txt") as f:
        info = f.read()
    
    if "Ada" in info:
        print("Welcome back, Ada!")

    Output

    Welcome back, Ada!
    
  18. Real version: This already reads real input — it loads a save file; no separate input() version.

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

  20. Error demo: this code stops with an error
    with open("missing.txt") as f:
        f.read()
  21. 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.

    • 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.