Skip to content
skillbld
Day 11 of 14 35 minopen()withtry / except

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.

Mind map · click a dot to fold, drag to pan

Writing and reading text files

Always open files with with: the file is closed automatically when the block ends.

main.py · editable
Output
Press Run to execute this code.
ModeMeaningIf the file existsIf it doesn't
"r"Read (default)Read itFileNotFoundError
"w"WriteErase it firstCreate it
"a"AppendAdd to the endCreate it
"x"CreateFileExistsErrorCreate it

Reading line by line

main.py · editable
Output
Press Run to execute this code.

Saving structured data as JSON

For lists and dictionaries, JSON is the easiest format to save and load:

main.py · editable
Output
Press Run to execute this code.

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.

Sketch
try runs the risky code. If an exception is raised, the matching except block handles it; if not, the else block runs. In both cases the finally block runs last for clean-up.
main.py · editable
Output
Press Run to execute this code.

Handling a missing file

main.py · editable
Output
Press Run to execute this code.

Common exceptions

ExceptionTypical cause
ValueErrorRight type, wrong value: int("abc")
TypeErrorWrong type: "a" + 1
KeyErrorMissing dictionary key
IndexErrorList index out of range
FileNotFoundErrorOpening a file that doesn't exist
ZeroDivisionErrorDividing by zero
main.py · editable
Output
Press Run to execute this code.

Raising your own errors

Use raise when your function receives something it can't work with:

main.py · editable
Output
Press Run to execute this code.

Recap

  • Use with open(path, mode) as f: so files always close; "w" overwrites, "a" appends.
  • json.dump and json.load save and load lists and dictionaries.
  • try / except handles errors; else runs on success; finally always runs.
  • Catch specific exceptions, and raise clear errors for bad input.

Knowledge check

Test what you learned

5 questions · pick an answer to see if you're right

0/5
  1. 1

    What does opening a file with mode "w" do if the file already exists?

  2. 2

    Why is "with open(...) as f:" preferred?

  3. 3

    In try / except / else / finally, when does the else block run?

  4. 4

    Which is the better way to catch errors?

  5. 5

    What does int("abc") raise?

Finished today's lesson?