Python 27 · Recover from file problems

Python lesson 27 of 50 · Intermediate · About 28 minutes

Help Pip distinguish a missing save, damaged JSON, invalid progress and a folder the program cannot read.

Pip presses a control in front of three mint-green mission screens.

Mission Use specific exceptions and a temporary save file to protect a previous valid checkpoint.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Save the complete checkpoint below as moonbase_27.py in a project folder and run python moonbase_27.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Read or write. Try the operation that can fail.. → Catch. Recognise the most specific error first.. → Recover. Keep the current state or the previous save..
Read or write → Catch → Recover

Understand the Python in this lesson

Read the explanations, then follow the worked example before changing the code.

Start with statements that might fail

The indented code under try: is the normal path. In load_game, Python reads the file, decodes JSON and calls validate_save. If a statement raises an exception, later statements in that try block are skipped. Python looks for a matching except below it.

Read handlers from the most specific to the broadest

FileNotFoundError is a kind of OSError. json.JSONDecodeError is a kind of ValueError. Python uses the first matching handler. Putting the specific cases first lets the radio give a better message than it could from one broad error type.

Group two errors that need one message

In except (UnicodeError, json.JSONDecodeError):, the comma inside parentheses lists two acceptable exception types. A decoding problem in the file’s text and a broken JSON layout both lead to Save is unreadable; current progress kept. The next handler handles readable data that failed the moonbase rules.

Prepare the new save somewhere separate

SAVE_FILE.with_suffix(".tmp") produces a new Path ending in .tmp. It does not rename the existing file. write_text writes the new JSON to that temporary location. Only after the write finishes does temporary.replace(SAVE_FILE) replace the old save.

Keep the radio usable after a problem

The save function catches OSError and returns a folder-related message if it cannot finish. The load handlers each return current with a message. The caller can still unpack state, message in the same way it does for a successful load.

How the pieces fit There are two kinds of protection in this checkpoint. Load tries to understand a file while keeping what the player already has. Save writes the new record completely before replacing the older one.

Follow one run, step by step
  1. Enter load in a fresh folder with no save.
    No save yet; current progress kept. Why read_text raises FileNotFoundError and the first handler matches.
  2. Try loading a separate test save containing only an opening brace.
    Save is unreadable; current progress kept. Why json.loads raises JSONDecodeError before validation can start.
  3. Load readable JSON with energy set to 99.
    Save has invalid data; current progress kept. Why Decoding succeeds, then validate_save raises ValueError for the impossible field.

Predict before you run If you put except OSError above except FileNotFoundError, which message would a missing file give?

Reveal the explanation

The first handler would give the broad Could not open save; current progress kept. message. Keep the missing-file case above it to preserve the more useful explanation.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills try and except, exception order, atomic replacement, recovery messages.

1. Distinguish the failures

The load code now has separate exception handlers. A missing file means you have no earlier checkpoint here. Invalid JSON means the text could not be decoded as a record. A value error after decoding means one of the game’s checks failed. Keeping the messages distinct helps you choose a next step without having to read a traceback.

def load_game(current):
    try:
        data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
        return validate_save(data), "Saved progress loaded."
    except FileNotFoundError:
        return current, "No save yet; current progress kept."
    except (UnicodeError, json.JSONDecodeError):
        return current, "Save is unreadable; current progress kept."

2. Handle specific exceptions before general ones

Check the order of the handlers. A missing file is also an OS error, and a JSON decoding error is a kind of value error. Put them in the reverse order and the general handler will run first. Compare the messages for a missing file and a save with a damaged opening brace.

except FileNotFoundError:
        return current, "No save yet; current progress kept."
    except (UnicodeError, json.JSONDecodeError):
        return current, "Save is unreadable; current progress kept."
    except ValueError:
        return current, "Save has invalid data; current progress kept."
    except OSError:
        return current, "Could not open save; current progress kept."

3. Write a complete save before replacing the old one

Save the text to a temporary filename in the same folder. When the write completes, replace the previous save using replace. If something stops the write early, the previous file remains. Run a normal save first. If you try hand-editing the game’s save to practise recovery, make a copy of it before changing the original.

def save_game(state):
    temporary = SAVE_FILE.with_suffix(".tmp")
    try:
        temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
        temporary.replace(SAVE_FILE)
    except OSError:
        return "Could not save progress. Check that this folder is writable."
    return "Progress saved to moonbase-save.json."

4. Match the fix to the error

A missing save can be fixed by making a new one. An unreadable save should be replaced with a known-good copy. A field problem needs a corrected value or a fresh save. Suggest a different player-facing line for each case, and leave enough detail for you to identify the original mistake.

Complete Python checkpoint · moonbase_27.py
import json
from pathlib import Path


WORLD = {
    "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None},
    "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"},
    "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"},
    "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None},
}
REQUIRED = {"Coil", "Cell"}
SAVE_FILE = Path("moonbase-save.json")


def new_mission():
    return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}


def can_repair(room, parts):
    return room == "Beacon" and REQUIRED.issubset(parts)


def describe(state):
    room, energy, cargo, _ = mission_snapshot(state)
    exits = ", ".join(WORLD[room]["exits"])
    parts = ", ".join(cargo) or "none"
    return f"{room} | energy {energy} | parts {parts} | exits {exits}"


def collect(state):
    item = WORLD[state["room"]]["part"]
    if item is None:
        return "There is no repair part here."
    if item in state["parts"]:
        return f"You already have the {item}."
    state["parts"].append(item)
    return f"Collected the {item}."


def repair(state):
    if can_repair(state["room"], state["parts"]):
        state["rescued"] = True
        return "Beacon restored! Pip has sent the rescue signal."
    return "Bring the Coil and the Cell to the Beacon."


def move(state, direction):
    destination = WORLD[state["room"]]["exits"].get(direction)
    if destination is None:
        return "That route is blocked."
    if state["energy"] == 0:
        return "Pip is out of energy."
    state["room"] = destination
    state["energy"] -= 1
    return f"Moved to {destination}."


def parse_command(text):
    words = text.lower().split()
    if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
        return "go", words[0]
    if len(words) == 2 and words[0] == "go":
        return "go", words[1]
    if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}:
        return words[0], ""
    return "", ""


def save_game(state):
    temporary = SAVE_FILE.with_suffix(".tmp")
    try:
        temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
        temporary.replace(SAVE_FILE)
    except OSError:
        return "Could not save progress. Check that this folder is writable."
    return "Progress saved to moonbase-save.json."


def validate_save(data):
    if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
        raise ValueError("expected four state fields")
    if type(data["room"]) is not str or data["room"] not in WORLD:
        raise ValueError("unknown room")
    if type(data["energy"]) is not int or not 0 <= data["energy"] <= 8:
        raise ValueError("bad energy")
    parts = data["parts"]
    if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
        raise ValueError("unknown part")
    if len(parts) != len(set(parts)):
        raise ValueError("duplicate part")
    if type(data["rescued"]) is not bool:
        raise ValueError("bad rescue flag")
    if data["rescued"] and not can_repair(data["room"], parts):
        raise ValueError("inconsistent rescue")
    return data


def load_game(current):
    try:
        data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
        return validate_save(data), "Saved progress loaded."
    except FileNotFoundError:
        return current, "No save yet; current progress kept."
    except (UnicodeError, json.JSONDecodeError):
        return current, "Save is unreadable; current progress kept."
    except ValueError:
        return current, "Save has invalid data; current progress kept."
    except OSError:
        return current, "Could not open save; current progress kept."


def mission_snapshot(state):
    return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]


def apply(state, verb, argument):
    if verb == "look":
        return describe(state)
    if verb == "go":
        return move(state, argument)
    if verb == "take":
        return collect(state)
    if verb == "repair":
        return repair(state)
    return "Unknown command."


def run():
    state = new_mission()
    print("Moonbase Rescue | Pip on duty")
    print(describe(state))
    print("Try look, go, take, repair or quit.")
    while not state["rescued"]:
        try:
            raw = input("Pip> ")
        except EOFError:
            print("Radio closed.")
            break
        verb, argument = parse_command(raw)
        if verb == "quit":
            print("Pip is on standby.")
            break
        if verb == "save":
            print(save_game(state))
            continue
        if verb == "load":
            state, message = load_game(state)
            print(message)
            continue
        print(apply(state, verb, argument))


if __name__ == "__main__":
    run()

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–26
Line 1 import json
Bring in json. Its module name gives you access to the tools it contains.
Line 2 from pathlib import Path
Bring Path into this file from pathlib. These names can now be used directly.
Lines 5–10 WORLD = { "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None}, "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"}, "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"}, "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 11 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 12 SAVE_FILE = Path("moonbase-save.json")
Work out the value on the right, then store it in SAVE_FILE. Represent a file location so the program can work with it.
Line 15 def new_mission():
Define new_mission, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 16 return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}
Leave this function now and hand the result back to the line that called it. Each colon pairs a key with its value.
Line 19 def can_repair(room, parts):
Define can_repair, a reusable piece of the program. Its input names are room, parts. The indented body runs when something calls it.
Line 20 return room == "Beacon" and REQUIRED.issubset(parts)
Leave this function now and hand the result back to the line that called it. With and, every check must be true. Check whether every item in this set appears in the other collection.
Line 23 def describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 24 room, energy, cargo, _ = mission_snapshot(state)
Give each returned value to the matching name, from left to right. Run mission_snapshot with the supplied inputs and come back here when it returns.
Line 25 exits = ", ".join(WORLD[room]["exits"])
Work out the value on the right, then store it in exits. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 26 parts = ", ".join(cargo) or "none"
Work out the value on the right, then store it in parts. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Lines 27–43
Line 27 return f"{room} | energy {energy} | parts {parts} | exits {exits}"
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 30 def collect(state):
Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 31 item = WORLD[state["room"]]["part"]
Work out the value on the right, then store it in item. The brackets look up a dictionary key or a position that starts at zero.
Line 32 if item is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 33 return "There is no repair part here."
Leave this function now and hand the result back to the line that called it.
Line 34 if item in state["parts"]:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection. The brackets look up a dictionary key or a position that starts at zero.
Line 35 return f"You already have the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 36 state["parts"].append(item)
Add the value to the end without replacing the earlier entries.
Line 37 return f"Collected the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 40 def repair(state):
Define repair, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 41 if can_repair(state["room"], state["parts"]):
Run the indented block only if this check is true. Run can_repair with the supplied inputs and come back here when it returns. The brackets look up a dictionary key or a position that starts at zero.
Line 42 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 43 return "Beacon restored! Pip has sent the rescue signal."
Leave this function now and hand the result back to the line that called it.
Lines 44–60
Line 44 return "Bring the Coil and the Cell to the Beacon."
Leave this function now and hand the result back to the line that called it.
Line 47 def move(state, direction):
Define move, a reusable piece of the program. Its input names are state, direction. The indented body runs when something calls it.
Line 48 destination = WORLD[state["room"]]["exits"].get(direction)
Work out the value on the right, then store it in destination. Look up a key. Use the given fallback, or None, if the key is missing.
Line 49 if destination is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 50 return "That route is blocked."
Leave this function now and hand the result back to the line that called it.
Line 51 if state["energy"] == 0:
Run the indented block only if this check is true. The brackets look up a dictionary key or a position that starts at zero.
Line 52 return "Pip is out of energy."
Leave this function now and hand the result back to the line that called it.
Line 53 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 54 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 55 return f"Moved to {destination}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 58 def parse_command(text):
Define parse_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 59 words = text.lower().split()
Work out the value on the right, then store it in words. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 60 if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Lines 61–75
Line 61 return "go", words[0]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 62 if len(words) == 2 and words[0] == "go":
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 63 return "go", words[1]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 64 if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 65 return words[0], ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 66 return "", ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 69 def save_game(state):
Define save_game, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 70 temporary = SAVE_FILE.with_suffix(".tmp")
Work out the value on the right, then store it in temporary. Build a path with a different ending. This does not rename any file yet.
Line 71 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 72 temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
Write text to the file using the chosen encoding. Turn Python data into JSON text. This step does not write a file.
Line 73 temporary.replace(SAVE_FILE)
Move the temporary file into the final save location.
Line 74 except OSError:
Run this part only when the try block raises OSError.
Line 75 return "Could not save progress. Check that this folder is writable."
Leave this function now and hand the result back to the line that called it.
Lines 76–90
Line 76 return "Progress saved to moonbase-save.json."
Leave this function now and hand the result back to the line that called it.
Line 79 def validate_save(data):
Define validate_save, a reusable piece of the program. Its input names are data. The indented body runs when something calls it.
Line 80 if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 81 raise ValueError("expected four state fields")
Stop this path and report ValueError("expected four state fields") to whoever called this code.
Line 82 if type(data["room"]) is not str or data["room"] not in WORLD:
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 83 raise ValueError("unknown room")
Stop this path and report ValueError("unknown room") to whoever called this code.
Line 84 if type(data["energy"]) is not int or not 0 <= data["energy"] <= 8:
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 85 raise ValueError("bad energy")
Stop this path and report ValueError("bad energy") to whoever called this code.
Line 86 parts = data["parts"]
Work out the value on the right, then store it in parts. The brackets look up a dictionary key or a position that starts at zero.
Line 87 if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 88 raise ValueError("unknown part")
Stop this path and report ValueError("unknown part") to whoever called this code.
Line 89 if len(parts) != len(set(parts)):
Run the indented block only if this check is true. Count the characters or items. Collect distinct values, with no duplicate entries.
Line 90 raise ValueError("duplicate part")
Stop this path and report ValueError("duplicate part") to whoever called this code.
Lines 91–105
Line 91 if type(data["rescued"]) is not bool:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value. The brackets look up a dictionary key or a position that starts at zero.
Line 92 raise ValueError("bad rescue flag")
Stop this path and report ValueError("bad rescue flag") to whoever called this code.
Line 93 if data["rescued"] and not can_repair(data["room"], parts):
Run the indented block only if this check is true. With and, every check must be true. The brackets look up a dictionary key or a position that starts at zero. The word not reverses which result counts as true.
Line 94 raise ValueError("inconsistent rescue")
Stop this path and report ValueError("inconsistent rescue") to whoever called this code.
Line 95 return data
Leave this function now and hand the result back to the line that called it.
Line 98 def load_game(current):
Define load_game, a reusable piece of the program. Its input names are current. The indented body runs when something calls it.
Line 99 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 100 data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
Work out the value on the right, then store it in data. Read JSON text or bytes and turn it back into Python data. Read a file and decode its contents into text.
Line 101 return validate_save(data), "Saved progress loaded."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run validate_save with the supplied inputs and come back here when it returns.
Line 102 except FileNotFoundError:
Run this part only when the try block raises FileNotFoundError.
Line 103 return current, "No save yet; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 104 except (UnicodeError, json.JSONDecodeError):
Run this part only when the try block raises (UnicodeError, json.JSONDecodeError).
Line 105 return current, "Save is unreadable; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Lines 106–122
Line 106 except ValueError:
Run this part only when the try block raises ValueError.
Line 107 return current, "Save has invalid data; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 108 except OSError:
Run this part only when the try block raises OSError.
Line 109 return current, "Could not open save; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 112 def mission_snapshot(state):
Define mission_snapshot, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 113 return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero. Collect ordered items in a tuple, whose entries cannot be reassigned.
Line 116 def apply(state, verb, argument):
Define apply, a reusable piece of the program. Its input names are state, verb, argument. The indented body runs when something calls it.
Line 117 if verb == "look":
Run the indented block only if this check is true.
Line 118 return describe(state)
Leave this function now and hand the result back to the line that called it. Run describe with the supplied inputs and come back here when it returns.
Line 119 if verb == "go":
Run the indented block only if this check is true.
Line 120 return move(state, argument)
Leave this function now and hand the result back to the line that called it. Run move with the supplied inputs and come back here when it returns.
Line 121 if verb == "take":
Run the indented block only if this check is true.
Line 122 return collect(state)
Leave this function now and hand the result back to the line that called it. Run collect with the supplied inputs and come back here when it returns.
Lines 123–137
Line 123 if verb == "repair":
Run the indented block only if this check is true.
Line 124 return repair(state)
Leave this function now and hand the result back to the line that called it. Run repair with the supplied inputs and come back here when it returns.
Line 125 return "Unknown command."
Leave this function now and hand the result back to the line that called it.
Line 128 def run():
Define run, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 129 state = new_mission()
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 130 print("Moonbase Rescue | Pip on duty")
Show the message or value in the output.
Line 131 print(describe(state))
Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
Line 132 print("Try look, go, take, repair or quit.")
Show the message or value in the output.
Line 133 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 134 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 135 raw = input("Pip> ")
Work out the value on the right, then store it in raw. Show the prompt and wait for the player to type a line. The answer starts as text.
Line 136 except EOFError:
Run this part only when the try block raises EOFError.
Line 137 print("Radio closed.")
Show the message or value in the output.
Lines 138–150
Line 138 break
Leave the nearest loop immediately and continue after it.
Line 139 verb, argument = parse_command(raw)
Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
Line 140 if verb == "quit":
Run the indented block only if this check is true.
Line 141 print("Pip is on standby.")
Show the message or value in the output.
Line 142 break
Leave the nearest loop immediately and continue after it.
Line 143 if verb == "save":
Run the indented block only if this check is true.
Line 144 print(save_game(state))
Show the message or value in the output. Run save_game with the supplied inputs and come back here when it returns.
Line 145 continue
Skip the rest of this pass and start the next loop check.
Line 146 if verb == "load":
Run the indented block only if this check is true.
Line 147 state, message = load_game(state)
Give each returned value to the matching name, from left to right. Run load_game with the supplied inputs and come back here when it returns.
Line 148 print(message)
Show the message or value in the output.
Line 149 continue
Skip the rest of this pass and start the next loop check.
Line 150 print(apply(state, verb, argument))
Show the message or value in the output. Run apply with the supplied inputs and come back here when it returns.
Lines 153–154
Line 153 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 154 run()
Run run with the supplied inputs and come back here when it returns.

Test the mission

  • Run with no save and type load. Check for No save yet.
  • Make a save, then damage a character in a copy and use it to test the unreadable message.
  • Test a valid save once more and check that loading restores the right room.

If something goes wrong

A damaged record gets the wrong explanation.
Make sure JSONDecodeError appears before ValueError, and FileNotFoundError before OSError.

Mission extension

Make a mini test table with one expected message for each kind of file problem.