Lesson 15 of 30
Lesson 15 ? Tiny text files
Title: Save and read simple notes
Description: Write text to a file and read it back with small examples.
Why it matters for kids: Files help programs remember things after they close.
1. Write a note
note = "Remember to feed the dragon."
with open("note.txt", "w") as file:
file.write(note)After running this, look for note.txt beside your Python file.
2. Read the note
with open("note.txt", "r") as file:
note = file.read()
print(note)3. Write many lines
with open("pets.txt", "w") as file:
file.write("cat
")
file.write("dog
")
file.write("rabbit
") means new line.
4. Read lines
with open("pets.txt", "r") as file:
pets = file.readlines()
for pet in pets:
print(pet.strip())strip() removes extra spaces and line breaks.
5. Easy examples
with open("score.txt", "w") as file:
file.write("100")with open("message.txt", "w") as file:
file.write("Python is fun!")with open("message.txt", "r") as file:
print(file.read())6. Mini challenge
Click each example to open it.
Example 1
Write Hello to a file.
Example 2
Read the file and print it.
Example 3
Write your name to a file.
Example 4
Write one pet to a file.
Example 5
Write three pets on new lines.
Example 6
Read all pet lines.
Example 7
Use strip on one line.
Example 8
Save a score as text.
Example 9
Read the saved score.
Example 10
Create favorite_foods.txt.