Week 6_Practice Exercises
Week 6_Practice Exercises
Before typing each of these statements, try to work out which exception they will raise.
If you are wrong, take a few moments to read the error message and understand why.
1. potato
2. 5/0
3. int('0.999')
4. round(3.14159, '2')
5. open('exam_answers.txt', 'r')
Save and run the program, then go to the folder you saved the program into and open “example.txt”
in Notepad. Write something into the file and try to save it. You should see an error:
Since the program didn’t close the file, it is still “locked” and can’t be written to by other programs.
Cancel the saving and close “example.txt”. Add the following line to the program and run it again:
f = open('example.txt', 'w') Python
f.write('Write this to the file.')
Open “example.txt” again. Is the file still empty? If so, it’s because the data that the program wrote
was written into a “buffer” in memory (which is faster), rather than writing it to the file on the disk
itself. The data in the buffer is only written to the file on the disk when you close the file. Add a line
to close the file, and now the program should work as intended:
f = open('example.txt', 'w') Python
f.write('Write this to the file.')
f.close()
CSP1150 Page 1
Task 3 – File Head Display
Write a program that asks the user for the name of a file. The program should display only
the first five lines of the file’s contents. If the file contains less than five lines, it should
display the file’s entire contents.
CSP1150 Page 1
Task 9 – Exception Handing
Modify the program that you wrote for Exercise 6 so it handles the following exceptions:
• It should handle any IOError exceptions that are raised when the file is opened and data is
read from it.
• It should handle any ValueError exceptions that are raised when the items that are read
from the file are converted to a number.
CSP1150 Page 1