Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← PYTHON FUNDAMENTALS LEVEL ONE PROFESSIONAL Β· Lesson 8 of 8

Module Seven

πŸ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
8
Module 7 Β· File I/O & Exceptions Β· Python for 13-year-olds

πŸ’Ύ Module 7 Β· File I/O & Exceptions

πŸ§‘β€πŸŽ“ for 13-year-olds save data & handle errors Β· 55 min
πŸ“ open Β· with Β· try/except

So far, everything your program does disappears when it ends. 😒 Want to save a high score, a to-do list, or a story? You need files! And when things go wrong β€” like trying to open a file that doesn’t exist β€” Python throws an exception. In this module you’ll learn to read, write, and handle errors like a real developer. Let’s go! πŸ’Ύ

1

Writing to a file ✍️

Use open() with a file name and a mode. The mode "w" means β€œwrite” β€” it creates a new file or overwrites an existing one. Then use .write() to put text in, and .close() when you’re done.

# Create a file and write to it
file = open("diary.txt", "w")
file.write("Dear diary, today I learned Python! 🐍\n")
file.write("It was awesome.\n")
file.close()

# ⚠️ "w" erases the old contents β€” use "a" to add instead
ModeWhat it does
"r"Read (default) β€” file must exist
"w"Write β€” creates or overwrites
"a"Append β€” adds to the end
"x"Create β€” fails if file already exists
πŸ“ Where does the file go? In the same folder as your .py file, unless you give a full path.
2

Reading a file πŸ“–

Use mode "r" to read. You can grab the whole file with .read(), or get a list of lines with .readlines(). You can even loop through the file line by line β€” the Pythonic way!

# Read the whole file
file = open("diary.txt", "r")
contents = file.read()
print(contents)
file.close()

# Loop through lines (cleaner)
file = open("diary.txt", "r")
for line in file:
print(line.strip()) # strip() removes the \n
file.close()

πŸ“‚ What's happening

open("diary.txt", "r") β†’ read / loop lines β†’ close()
🧠 Always close your files! It frees them up so other programs can use them. Or better β€” use the with statement (next step!).
3

The with statement: auto-close magic ✨

The with statement automatically closes the file for you β€” even if something crashes! It’s the recommended way to work with files. No more forgetting .close().

# βœ… Best practice β€” auto-closes!
with open("diary.txt", "w") as file:
file.write("New entry: Python files are easy!\n")

with open("diary.txt", "r") as file:
for line in file:
print(line.strip())
🎯 Rule of thumb: If you see open() without with, it’s a warning sign. Use with β€” your future self will thank you!
4

Exceptions: when things go wrong πŸ’₯

An exception is an error that happens while your program is running. Python β€œraises” it and β€” if you don’t catch it β€” your program crashes. Common ones:

ExceptionHappens when…
FileNotFoundErrorYou try to open a file that doesn’t exist
ValueErrorWrong value, like int("hello")
ZeroDivisionErrorDividing by zero
IndexErrorUsing an index that’s too big
TypeErrorMixing types, like "a" + 1
# This crashes! πŸ’₯
open("ghost.txt", "r")
# FileNotFoundError: [Errno 2] No such file or directory: 'ghost.txt'
πŸ”₯ Don’t panic! Exceptions aren’t the end β€” they’re Python’s way of saying β€œhey, something needs attention here.”
5

Catching exceptions with try / except πŸ›‘οΈ

Wrap risky code in try, and handle the problem in except. Now your program can recover gracefully instead of crashing.

try:
with open("ghost.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("That file doesn't exist! πŸ“‚βŒ")

# Keep going β€” the program survives!
print("Program continues... πŸŽ‰")

πŸ›‘οΈ How try/except flows

try: risky code β†’ No error? Great, skip except
error happens β†’ except catches it β†’ handle nicely
🎯 Catch specific exceptions. Use except FileNotFoundError rather than a bare except: β€” it hides real bugs otherwise.
6

Bonus powers: else & finally πŸ”§

Two extra blocks make error handling even smarter: else runs only if no exception happened, and finally runs no matter what β€” perfect for cleanup.

try:
number = int(input("Enter a number: "))
except ValueError:
print("That's not a number! πŸ˜…")
else:
print(f"Nice! You entered {number} βœ…")
finally:
print("Done β€” this always runs! 🏁")
🧠 Memory trick: try = attempt, except = plan B, else = victory speech, finally = always says goodbye.
7

Put it all together πŸ—οΈ

Here’s a mini program that saves a high score to a file, reads it back, and handles errors gracefully β€” using everything from this module.

def save_score(score):
with open("highscore.txt", "w") as f:
f.write(str(score))

def load_score():
try:
with open("highscore.txt", "r") as f:
return int(f.read())
except FileNotFoundError:
print("No high score saved yet. πŸ†•")
return 0

save_score(950)
print(f"High score: {load_score()} πŸ†")
πŸ§ͺ Try it! Save as highscore.py, run it once, then delete highscore.txt and run again β€” watch the exception handler kick in!

πŸ† Mini challenge: A personal journal app

Create a file called journal.py that lets you add entries to a journal file and read them back β€” with proper error handling. Aim for these features:

  • Write: ask the user for an entry and append it to journal.txt (mode "a").
  • Read: open the file and print each line nicely.
  • Handle: if the journal doesn’t exist yet when reading, show a friendly message with try / except FileNotFoundError.
  • Bonus: add a finally block that prints β€œJournal session complete βœ…β€.
# Starter code – build it out!
def add_entry(text):
with open("journal.txt", "a") as f:
f.write(text + "\n")

def read_journal():
try:
# your code here
pass
except FileNotFoundError:
# your friendly message
pass

add_entry("Today I learned about files! πŸ’Ύ")
read_journal()

πŸ““ Pro tip: Add a timestamp to each entry using import datetime β€” then every entry feels like a real diary!

πŸ§‘β€πŸ« Remember: Use with open(...) as f: for files, and try / except for anything that might fail. Your code just became much tougher!

πŸ† Get Certified

πŸ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

πŸŽ“ Sign Up to Get Certified
πŸ› οΈ Practice Tools
Hands-on simulators & labs - subscription required.
β†’
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
β†’