Page 133 -
P. 133
files and exceptions
Add more error-checking code…
If you’re a fan of the “let’s not let errors happen” school of thinking, your
first reaction will be to add extra code to check to see if the data file exists
before you try to open it, right?
Let’s implement this strategy. Python’ s os module has some facilities that can
help determine whether a data file exists, so we need to import it from the
Standard Library, then add the required check to the code:
import os
Check whether
the file exists.
if os.path.exists('sketch.txt'):
data = open('sketch.txt')
for each_line in data:
if not each_line.find(':') == -1:
All of this (role, line_spoken) = each_line.split(':', 1)
code remains print(role, end='')
unchanged.
print(' said: ', end='')
print(line_spoken, end='')
data.close()
Inform the else:
user of the
bad news. print('The data file is missing!')
A quick test of the code confirms that this new problem is dealt with properly. With this new version of your code
in IDLE’s edit window, press F5 to confirm all is OK.
>>> ================================ RESTART ================================
>>> Exactly what was expected. Cool.
The data file is missing!
>>>
you are here 4 97