Files and exceptions
Programs need to save and load data, and they need to cope with things going wrong: a missing file, bad user input, a network error. This lesson covers both.
The editors here have their own little in-memory file system, so you can create and read files safely. They disappear when the run ends.
Writing and reading text files
The with statement closes the file automatically, even if an error happens. Always use it.
Reading line by line
Looping over the file reads one line at a time, so it works even for huge files.
| Mode | Meaning |
|---|---|
"r" |
Read (default). Error if the file doesn't exist. |
"w" |
Write. Creates the file, or erases it first. |
"a" |
Append to the end. |
"x" |
Create; error if it already exists. |
"b" |
Add for binary files: "rb", "wb" (images, PDFs) |
Specify encoding="utf-8" on real projects so accented letters and emoji behave the same on every computer.
Paths with pathlib
The modern way to work with files and folders is pathlib:
CSV and JSON
Two formats you'll meet constantly. Both have built-in modules:
Exceptions
When something goes wrong, Python raises an exception. If nothing handles it, the program stops with a traceback:
try / except
Handle errors you expect, and decide what should happen instead:
else and finally
Common exceptions
| Exception | Typical cause |
|---|---|
ValueError |
Right type, wrong value: int("abc") |
TypeError |
Wrong type: "a" + 1 |
KeyError |
Missing dict key |
IndexError |
List index out of range |
FileNotFoundError |
Opening a file that isn't there |
ZeroDivisionError |
Dividing by zero |
AttributeError |
None.upper(), a typo in a method name |
Raising your own
You can also define custom exception classes (you'll learn classes soon):
Good practice
- Catch specific exceptions. A bare
except:also hides bugs (and even Ctrl+C). - Keep the
tryblock small: only the lines that can actually fail. - Don't silently ignore errors. At least log them.
- "It's easier to ask forgiveness than permission" (EAFP): in Python, trying and catching is often cleaner than checking everything first.
Practice
- Write a list of 5 shopping items to
shopping.txt, then read it back and print it numbered. - Write a function
safe_int(text, default=0)that returns the number, or the default if conversion fails. - Save a dict of three students and their marks to
marks.json, load it, and print the average.
1.Why use with open(...) as f:?
2.What does opening a file with mode "w" do to an existing file?
3.When does the finally block run?