Login

Back

Handling IO exceptions - Answers

This activity will make more sense if you have done some of the activities in the 'File operations' section.

Q1. Get this code working in Python: 

#Handling an error associated with writing to and reading from a file.
try:
    writefile = open("testFile", 'w')
    writefile.write("This is a lot of data that I want to save to a file")
    print('You can put some more lines of code here.')
except IOError:
    print ("Error: can't write the data to the file for some reason.")
else:
    print ("Content written to the file successfully.")
    writefile.close()

Q2. The above code uses a try construction that follows this pattern:

try
    do these instructions
except XXXX
    do these instructions if Python spots an IO error.
else
    do these instructions if Python was able to run the code without an exception

The name of the file that Python writes is testFile. It is stored in the same directory (the same folder as the Python program). 
Q3. Now get this code working (note that the filename is deliberately called 'toastFile'):

#Handling an IO error

try:
    readfile = open("toastFile", 'r')
    print(readfile.read())
    print('File read successfully.')
except IOError:
    print ("Error: can't find file or read data.")
else:
    print ("Read content from the file successfully.")
    readfile.close()

The try block fails because toastFile doesn't exist. This is picked up by the IOError exception so the block of code in the except IOError section is run. The program displays Error: can't find file or read data.
Q4. When you change the filename from toastFile to testFile and rerun the program, it works. It displays whatever is in the file along with File read successfully and Read content from the file successfully. The else part of the construction ran as well because no error was found.
Q5. When you change the access mode from 'r' to 'w' so that you only have write access rights to the file, you get this error message: Error: can't find file or read data.

Back