Week 8 of 106 hours5 exercises
Week 8: Errors, files and JSON
Handle problems calmly with try and except, read and write files, and save structured data as JSON.
By the end of this week you can
- Read an error message and find the line that caused it
- Catch errors with try and except
- Read and write text files with with
- Convert data to and from JSON
Reading error messages
When something goes wrong Python stops and prints a traceback. Read it from the bottom: the last line names the kind of error (such as ValueError or ZeroDivisionError) and says what happened, and the lines above point to where. Most errors fix themselves once you read that last line slowly.
Common ones: SyntaxError (the code is not valid Python, often a missing colon or bracket), NameError (a name that does not exist, often a typo), TypeError (the wrong kind of value, such as adding text to a number), IndexError, KeyError and ValueError (right type, wrong content, like int("abc")).
Here we catch the errors so the program carries on and prints a message instead of stopping.
try, except, else, finally
Put the risky code in try, and what to do about a problem in except. Name the specific error you expect; a bare except hides mistakes you did not plan for. else runs only if nothing went wrong, and finally runs always, which is useful for tidy-up work.
Use try when something outside your control might fail, such as typed input, a file or a network. Do not use it to hide bugs in your own logic.
raise lets you create an error yourself when your function receives something it cannot work with.
Reading and writing files
open(name, mode) gives you a file. Modes: "r" read, "w" write (replaces the file), "a" append. Always use with open(...) as f: because it closes the file for you, even if an error happens inside.
f.read() gives the whole text, f.readlines() gives a list of lines, and looping over f gives one line at a time. Lines keep their newline at the end, so use strip() when you need clean text. On this page, files live in a temporary space inside your browser and disappear when you leave, which is perfect for practice.
\n is a new line. We used "a" the second time so the earlier lines stay.
JSON: saving structured data
JSON is a plain-text format for dictionaries, lists, text, numbers and True/False (written true/false). Almost every web service speaks it. The json module turns Python data into JSON text with dumps() and back with loads(); dump() and load() do the same straight to and from a file.
indent=2 only makes the text easier to read. Tuples come back as lists, because JSON has no tuples.
Common mistakes
- Using a bare except: that hides every error, including typos in your own code.
- Opening a file with "w" when you wanted to add to it. "w" erases what was there.
- Forgetting that a line read from a file ends with a newline.
- Wrapping the whole program in try so that nothing ever fails loudly.
Quick recap
- Read the last line of a traceback first.
- try/except with a named error keeps programs running on bad input.
- with open(...) handles closing; "w" replaces, "a" appends.
- json turns Python data into text and back.
Practise this week
Work through the 5 exercises for Week 8. Each one tells you which tests pass, and has a hint and a solution if you get stuck.
Check your understanding
Pick an answer for each question, then press Check answers.
This course is for learning. The Python engine runs in your browser and your code is never sent to us.