CSP1150/CSP5110: Programming Principles
Practice Exercises: Files and Exception Handling
Task 1 – Concept Revision in the Python Shell
Let’s revise the concepts from this module by typing some simple statements into the Python Shell.
Feel free to deviate from these exercises and experiment!
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')
Task 2 – Unclosed Files
This task simply demonstrates the importance of closing a file once you have finished using it.
Create a new file in the Python Editor and copy-paste the following code into it:
f = open('[Link]', 'w') Python
Save and run the program, then go to the folder you saved the program into and open “[Link]”
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 “[Link]”. Add the following line to the program and run it again:
f = open('[Link]', 'w') Python
[Link]('Write this to the file.')
Open “[Link]” 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('[Link]', 'w') Python
[Link]('Write this to the file.')
[Link]()
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.
Task 4 – Line Numbers
Write a program that asks the user for the name of a file. The program should display the
contents of the file with each line preceded with a line number followed by a colon. The
line numbering should start at 1.
Task 5 – High Score
Assume that a file named [Link] exists on the computer’s disk. It contains a series of
records, each with two fields – a name, followed by a score (an integer between 1 and 100).
Write a program that displays the name and score of the record with the highest score, as
well as the number of records in the file. (Hint: Use a variable and an “if” statement to
keep track of the highest score found as you read through the records, and a variable to
keep count of the number of records.)
Task 6 – Sum and Average of Numbers
Assume a file containing a series of integers is named [Link] and exists on the computer’s disk.
Write a program that reads all of the numbers stored in the file and calculates
their sum and average using two user defined functions. The program should prompt the user to
select to calculate either the sum or the average of the set of numbers.
Task 7 – Word List File Writer
Write a program that asks the user how many words they would like to write to a file, and
then asks the user to enter that many words, one at a time. The words should be written
to a file.
Task 8 – Word List File Reader
This exercise assumes you have completed the Programming Exercise 7, Word List File Writer. Write
another program that reads the words from the file and displays the following data:
• The number of words in the file.
• The longest word in the file.
• The average length of all of the words in the file.
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.
Task 10 – Golf Scores
The Springfork Amateur Golf Club has a tournament every weekend. The club president has asked
you to write two programs:
1. A program that will read each player’s name and golf score as keyboard input, then save
these as records in a file named [Link]. (Each record will have a field for the player’s name
and a field for the player’s score.)
2. A program that reads the records from the [Link] file and displays them.
Task 11 – Personal Web Page Generator
Write a program that asks the user for his or her name, then asks the user to enter a sentence that
describes himself or herself. Here is an example of the program’s screen:
Enter your name: Julie Taylor.
Describe yourself: I am a computer science major, a member of the Jazz club, and I hope to
work as a mobile app developer after I graduate.
Once the user has entered the requested input, the program should create an HTML file,
containing the input, for a simple Web page. Here is an example of the HTML content,
using the sample input previously shown:
<html>
<head>
</head>
<body>
<center>
<h1>Julie Taylor</h1>
</center>
<hr />
I am a computer science major, a member of the Jazz club, and I hope to work as a
mobile app developer after I graduate.
<hr />
</body>
</html>
CSP1150 Page 1