Save data that outlives your program and handle things that go wrong. Read and write files safely with with, and catch errors with try / except.
By the end of today you can
- Write and read text files with open() and with
- Choose the right file mode ("r", "w", "a")
- Save and load structured data as JSON
- Catch and handle errors with try / except / else / finally
- Raise your own errors with clear messages
Everything so far vanished when the program stopped. Today you'll make data last by writing it to files, and make programs robust by handling errors instead of crashing.
Writing and reading text files
Always open files with with: the file is closed automatically when the block ends.
| Mode | Meaning | If the file exists | If it doesn't |
|---|---|---|---|
"r" | Read (default) | Read it | FileNotFoundError |
"w" | Write | Erase it first | Create it |
"a" | Append | Add to the end | Create it |
"x" | Create | FileExistsError | Create it |
Reading line by line
Saving structured data as JSON
For lists and dictionaries, JSON is the easiest format to save and load:
When things go wrong: exceptions
When Python hits a problem it raises an exception. Unhandled, it stops the program with a traceback. With try / except you decide what happens instead.
Handling a missing file
Common exceptions
| Exception | Typical cause |
|---|---|
ValueError | Right type, wrong value: int("abc") |
TypeError | Wrong type: "a" + 1 |
KeyError | Missing dictionary key |
IndexError | List index out of range |
FileNotFoundError | Opening a file that doesn't exist |
ZeroDivisionError | Dividing by zero |
Raising your own errors
Use raise when your function receives something it can't work with:
Recap
- Use
with open(path, mode) as f:so files always close;"w"overwrites,"a"appends. json.dumpandjson.loadsave and load lists and dictionaries.try/excepthandles errors;elseruns on success;finallyalways runs.- Catch specific exceptions, and
raiseclear errors for bad input.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
What does opening a file with mode "w" do if the file already exists?
- 2
Why is "with open(...) as f:" preferred?
- 3
In try / except / else / finally, when does the else block run?
- 4
Which is the better way to catch errors?
- 5
What does int("abc") raise?
Finished today's lesson?