Variables disappear when your program ends. Files don't. Saving to a file is how a game keeps your high score, or how a script keeps notes. Python makes this short.
WRITING A FILE
with open("scores.txt", "w") as f:
f.write("Ana 120\n")
f.write("Ivo 95\n")
print("saved")saved
"w"means write. It creates the file, or replaces it if it already exists.\nstarts a new line.withcloses the file for you automatically. Always use it.
READING A FILE
with open("notes.txt", "w") as f:
f.write("buy apples\nfeed snek\n")
with open("notes.txt") as f:
for line in f:
print("-", line.strip())- buy apples
- feed snek
strip() removes the invisible newline at the end of each line.
ADDING TO A FILE
with open("log.txt", "w") as f:
f.write("level 1 done\n")
with open("log.txt", "a") as f:
f.write("level 2 done\n")
with open("log.txt") as f:
print(f.read())level 1 done
level 2 done
"a" means append: add to the end and keep what is already there.
SAVING DATA WITH JSON
To save lists and dictionaries, use the built-in json module.
import json
save = {"player": "Mia", "level": 4, "items": ["key", "map"]}
with open("save.json", "w") as f:
json.dump(save, f)
with open("save.json") as f:
loaded = json.load(f)
print(loaded["level"], loaded["items"][0])4 key
with open("t.txt", "w") as f:
f.write("A")
with open("t.txt", "w") as f:
f.write("B")
with open("t.txt") as f:
print(f.read())"w" replaces the whole file. The second write wipes "A", so only "B" is left. Use "a" to keep old content.COMMON BEGINNER MISTAKES
f.write(5) fails: write text, like f.write(str(5)), or use json.PRACTICE IT, DON'T JUST READ IT
In File Fortress you build a high-score table that is saved to a file, step by step, with real Python on your phone.
PLAY FILE FORTRESS ▸FAQ
What is the difference between "w" and "a" when opening a file?
"w" creates the file or replaces everything in it. "a" adds to the end and keeps what is already there.
Why should I use with open()?
It closes the file automatically, even if an error happens, so your data is saved properly.
How do I save a list or dictionary to a file?
Use the json module: json.dump(data, f) to save and json.load(f) to read it back.