Kids Coding
Tiny Files
Save a high score or a story to a file. Read it back next time.
KidsIntermediateTiny Files
Save something for later
A file keeps text after the program ends. You open it, write or read, and close it. with open(...) closes it for you.
Write, then read
with open("note.txt", "w", encoding="utf-8") as file:
file.write("High score: 12\n")
with open("note.txt", "r", encoding="utf-8") as file:
text = file.read()
print(text)"w" writes (and replaces). "r" reads. encoding="utf-8" keeps letters safe.
What this is for
- A high score.
- A story you generated.
- A list of names.
Real life
A high score on a handheld game that is still there tomorrow.
Memory forgets when the program ends. A file is the sticker on the fridge.
Save the high score
with open("highscore.txt", "w", encoding="utf-8") as file:
file.write("15")
with open("highscore.txt", "r", encoding="utf-8") as file:
best = file.read()
print("Best so far:", best)Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Write hello to hi.txt, then read the file and print it.
Show solution
with open("hi.txt", "w", encoding="utf-8") as file:
file.write("hello")
with open("hi.txt", "r", encoding="utf-8") as file:
print(file.read())