Files and saving data
Write data to disk and read it back: open, with open(), and split() for parsing saved lines into dictionaries.
What You'll Learn
- Split a string into pieces with split() to parse saved data
- Write text to a file with open() in write and append mode
- Read files back with read() and readlines()
- Always use with open() to close files safely
In this lesson:
- Cut a saved line into pieces with
split()so you can parse it - Write data to a file with
open()in write ("w") and append ("a") mode - Read it back with
read()andreadlines() - Use
with open()so files always close safely, then save and load your hero
Last lesson you packed your hero into one tidy dictionary. The catch you ran into at the end: everything you build still vanishes when the program ends. Close the window and the dictionary is gone. Let's fix that.
In this lesson you put data on disk so it survives, and you read it back the next time the program runs. That's a save/load system. The trick that makes loading work is one string method, so we'll start there.
The split() method
Before you can read a save back into a dictionary, you need to chop each saved line into its pieces. That's the job of split(). It takes a string and cuts it into a list. By default, it splits on spaces:
Result:
['Flamarion', 'fire', '95', '28']
You can also specify a different separator. For example, if the data is separated by commas, you can split on the comma and rebuild a dictionary from the pieces:
Result:
['Aquadon', 'water', '110', '22']
{'name': 'Aquadon', 'type': 'water', 'hp': 110, 'attack': 22}
We wrapped HP and attack in int() because split() always returns strings, even when they look like numbers. That bites people loading data from files, which is exactly what you're about to do.
Working with files
[!WARNING] Files reset on reload The playground filesystem is temporary. Files you write here disappear when you reload the page, that's normal. The code is exactly what you'd run on your own computer, where the file would stay. Writing then reading in the same run (like every example below) works fine.
Now the main event. To write to a file, you use open() with the "w" (write) mode:
A few important things:
"w"means "write". If the file already exists, the old content is erased"a"(append) adds to the end without erasing what was there before"\n"creates a new line in the filestr(value)converts numbers to text, becausewrite()only accepts strings- Do not forget
file.close(), otherwise data might be lost
Reading files
To load data back, you open the file with the "r" (read) mode:
Result:
=== Save Game ===
name: Flamarion
type: fire
hp: 95
attack: 28
If you want to read line by line, use readlines():
This is useful when you want to process each line separately, for example to reconstruct a dictionary from saved data. Here's where the split() you just learned earns its keep:
Result:
Loaded creature: {'name': 'Flamarion', 'type': 'fire', 'hp': '95', 'attack': '28'}
The with open() syntax
In the examples above, you had to remember close() after every open(). Forget it once and your data might not fully save, or the file stays locked. Easy to forget, so it's safer not to rely on remembering.
The fix is with open(). It closes the file for you when the block ends, even if the code inside it crashes:
Result:
Saved successfully!
name: Breezel
type: wind
hp: 80
attack: 24
Always use with open() instead of plain open(). It is safer, cleaner, and you do not have to worry about forgetting to close the file.
Exercise : Save hero progress
Exercise : Save and load hero progress
Exercise : Event journal
Your game grows: the save system
Last lesson your hero became a dictionary. Now that dictionary gets a save system: write it to a file, then load it straight back into the game. This is the same save_game / load_game pair the final game will use, just smaller.
Run it and the hero comes back exactly as you saved it. On your own computer, that file would still be there tomorrow.
Next: stop the crashes
Your save/load works, but it's fragile. Load a file that isn't there and the program dies. Let a player type "three" instead of 3 and your menu dies too. Both of those crash a demo at the worst moment.
Next lesson, Modules and handling errors, has two fixes. First you'll borrow ready-made code with modules (random for encounters, os for checking a file exists before you load it). Then you'll keep the program alive on bad input with try/except. After that, you ship the whole game.
Test Your Knowledge
Check how well you understood the lesson with these 3 questions.

