Enter. At the Please enter file to open: prompt, type testfile and
press Enter. This should complete successfully, and you should receive the message
File testfile opened successfully!, as shown below.
Click here to view code image
pi@raspberrypi ~ $ python3 py3prog/script1704.py
Please enter file to open: testfile
File testfile opened successfully!
pi@raspberrypi ~ $
- Now test your script again by typing python3 py3prog/script1704.py
and pressing Enter. At the Please enter file to open: prompt, type
nofile and press Enter. This should cause the script to abruptly halt (assuming that
you do not have a file called nofile), and you should get an ugly traceback
message similar to what is shown below:
Click here to view code image
pi@raspberrypi ~ $ python3 py3prog/script1704.py
Plvease enter file to open: nofile
Traceback (most recent call last):
File "py3prog/script1704.py", line 46, in <module>
main()
File "py3prog/script1704.py", line 42, in main
open_it (file_name)
File "py3prog/script1704.py", line 32, in open_it
my_file=open(file_name,'r')
IOError: [Errno 2] No such file or directory: 'nofile'
pi@raspberrypi ~ $
Obviously, you need to do more to get script1704.py into shape.
- Open script1704.py in a script editor again. Modify the open_it function so
that it looks as shown below:
Click here to view code image
def open_it (file_name): #Open file name
#
try:
my_file=open(file_name,'r')
print ("File", file_name, "opened successfully!")
my_file.close()
#
except Exception as open_error:
print ("An error exception has been raised.")
print ("The error message is:")
print (open_error)
print ()
return ()
#
- Notice that the except statement uses Exception as the name of the exception.
This is the overall base group for exceptions. In order to catch the exception using