Page 115 -
P. 115
files and exceptions
Know your data
Your code worked fine for a while, then crashed with a runtime error. The
problem occurred right after the line of data that had the Man saying, “You
most certainly did not!”
Let’s look at the data file and see what comes after this successfully processed
line:
M a n : You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
The error occurs AFTER this line
Other Man: Anyway, I did.
Man: You most certainly did not! of data.
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Notice anything?
Notice anything about the next line of data?
The next line of data has two colons, not one. This is enough extra data
to upset the split() method due to the fact that, as your code currently
stands, split()expects to break the line into two parts, assigning each to
role and line_spoken, respectively.
When an extra colon appears in the data, the split() method breaks the Do this!
line into three parts. Your code hasn’t told split() what to do with the third
part, so the Python interpreter raises a ValueError, complains that you
have “too many values,” and terminates. A runtime error has occurred.
To help diagnose this
problem, let’s put your
code into its own file called
sketch.py. You can copy
What approach might you take to solve this data- and paste your code from
processing problem? the IDLE shell into a new
IDLE edit window.
you are here 4 79