Victor Jeman Academy
Python Fundamentals8 min

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() and readlines()
  • 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:

text
['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:

text
['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

Scriere si citire fisiere
Dictionar (memorie)
creatura = {
"nume": "Flamarion"
"tip": "foc"
"hp": 95
"atac": 28
}
save_game.txt (disc)
(fisier gol)
Rezultat citire (program)
(nimic inca)
open("w") → scrie pe disc
|
open("r") → citeste din disc
apasa "Scrie in fisier" apoi "Citeste fisierul" ca sa vezi fluxul complet

[!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 file
  • str(value) converts numbers to text, because write() 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:

text
=== 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:

text
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:

text
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

Write a program that saves the hero's data to a file called "hero_save.txt". The hero has: name="Aldric", hero_class="Warrior", hp=95, attack=25, defense=15, gold=120. Write each stat on a separate line in the format "key:value". Use with open() for safety.

Exercise : Save and load hero progress

Write a program that saves the hero's data to "hero_save.txt", then reads it back. First write each stat on its own line in the format "key:value". Then open the file again, split each line by ":", and reconstruct the hero dictionary. Display the loaded hero stats.

Exercise : Event journal

Write a program that keeps an event journal. Start by creating "journal.txt" with a header line. Then loop: the user can (1) Add an event (appended to the file), (2) Read the journal (display everything in the file), (3) Exit. Use with open() in append mode ("a") for writing and read mode ("r") for reading.

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.

Question 1 of 3

What does the split() method do?