computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🗂️

🎓

⏱ 30 min

Free

Files & Error Handling

Save and load data with files, use with-blocks, and handle errors like a pro.

🎯 What you will learn

  • Write and read text files
  • Use with to open files safely
  • Handle specific exceptions

👋 Let’s get started!

Programs forget everything when they stop… unless they save to a FILE 💾. High scores, notes, settings — all live in files. Let’s write and read them safely.

🪜 Step by step

1. ✍️ Writing

“w” writes (and replaces). with closes the file automatically.

with open("notes.txt", "w") as f:
    f.write("Buy milk\n")
    f.write("Practice Python\n")
2. 📖 Reading

Read the whole file or loop line by line.

with open("notes.txt") as f:
    for line in f:
        print("-", line.strip())
3. 🛡️ Specific exceptions

Catch the exact error you expect, and use finally for clean-up.

try:
    with open("missing.txt") as f:
        print(f.read())
except FileNotFoundError:
    print("No file yet — starting fresh!")

🧪 Try it!

Change the code and press ▶ Run to see what happens. You can’t break anything!

High-score saver

scores = {"Ana": 120, "Ben": 95}

with open("scores.txt", "w") as f:
    for name, s in scores.items():
        f.write(f"{name},{s}\n")

with open("scores.txt") as f:
    for line in f:
        name, s = line.strip().split(",")
        print(f"{name}: {s} points")

Append to a log

with open("log.txt", "a") as f:
    f.write("Game started\n")
print("Saved!")

📖 Key words

Tap a card to flip it over!

File mode
"r" read, "w" write, "a" append 📝
with
Opens and auto-closes a file 🔒
Exception
An error you can catch 🛡️
finally
Runs no matter what 🧹

🏆 Challenge

Write the three colors to colors.txt (one per line), then read the file and print how many lines it has.

Challenge

colors = ["red", "green", "blue"]

Knowledge Check Quiz

  1. Which mode adds to the end of a file?
  2. Why use with open(…)?
  3. Which error happens if the file doesn’t exist?
← Previous lesson
Next lesson →