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:andf.write(...). -
Read a whole file with
f.read(), or one line at a time withfor 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.\nis the invisible newline that ends a line.with open("savegame.txt", "w") as f: f.write("1200\n") print("Saved one score.")Scroll the code for more ↓
Output
Saved one score.The
withblock openssavegame.txtfor 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.")Scroll the code for more ↓
Output
Saved 5 scores.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.")Scroll the code for more ↓
Output
Saved the settings.A different file can hold mixed lines — a name, a number, and a word — for the player's settings.
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.")Scroll the code for more ↓
(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)Scroll the code for more ↓
Output
1200 850 990 1430 760f.read()returns the entire file as one string — exactly what was saved.with open("savegame.txt") as f: for line in f: print(line)Scroll the code for more ↓
Output
1200 850 990 1430 760One 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())Scroll the code for more ↓
Output
1200 850 990 1430 760.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)Scroll the code for more ↓
Output
['1200', '850', '990', '1430', '760']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)Scroll the code for more ↓
Output
[1200, 850, 990, 1430, 760]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.
filenamesays which file to read;returnsends 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")Scroll the code for more ↓
Output
Loaded 5 scoresReal 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
into search it for the player's name.with open("settings.txt") as f: info = f.read() if "Ada" in info: print("Welcome back, Ada!")Scroll the code for more ↓
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.
Error demo: this code stops with an error with open("missing.txt") as f: f.read()Scroll the code for more ↓
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'FileNotFoundErrortells 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 thewithblock closes it for you. -
\nends 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, andint()turns each line back into a number. -
A
FileNotFoundErrormeans the file does not exist yet: save first, then load.
You can now make a game remember its scores between runs.
-