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! πΎ
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.
| Mode | What 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 |
.py file,
unless you give a full path.
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!
with statement (next step!).
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().
open() without with,
itβs a warning sign. Use with β your future self will thank you!
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:
| Exception | Happens when⦠|
|---|---|
FileNotFoundError | You try to open a file that doesnβt exist |
ValueError | Wrong value, like int("hello") |
ZeroDivisionError | Dividing by zero |
IndexError | Using an index thatβs too big |
TypeError | Mixing types, like "a" + 1 |
try / except π‘οΈ
Wrap risky code in try, and handle the problem in except.
Now your program can recover gracefully instead of crashing.
except FileNotFoundError
rather than a bare except: β it hides real bugs otherwise.
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.
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.
highscore.py, run it once, then delete
highscore.txt and run again β watch the exception handler kick in!
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:
journal.txt (mode "a").try / except FileNotFoundError.finally block that prints βJournal session complete β
β.
π Pro tip: Add a timestamp to each entry using import datetime β
then every entry feels like a real diary!
with open(...) as f: for files, and
try / except for anything that might fail. Your code just became much tougher!