Chapter 6 Files Exceptions
Chapter 6 Files Exceptions
TOPICS
6.1 Introduction to File Input and Output 6.3 Processing Records
6.2 Using Loops to Process Files 6.4 Exceptions
CONCEPT: When a program needs to save data for later use, it writes the data in a file.
The data can be read from the file at a later time.
The programs you have written so far require the user to reenter data each time the pro-
gram runs, because data stored in RAM (referenced by variables) disappears once the pro-
gram stops running. If a program is to retain data between the times it runs, it must have a
way of saving it. Data is saved in a file, which is usually stored on a computer’s disk. Once
the data is saved in a file, it will remain there after the program stops running. Data stored
in a file can be retrieved and used at a later time.
Most of the commercial software packages that you use on a day-to-day basis store data in
files. The following are a few examples:
• Word processors. Word processing programs are used to write letters, memos, reports,
and other documents. The documents are then saved in files so they can be edited and
printed.
• Image editors. Image editing programs are used to draw graphics and edit images,
such as the ones that you take with a digital camera. The images that you create or
edit with an image editor are saved in files.
• Spreadsheets. Spreadsheet programs are used to work with numerical data. Numbers
and mathematical formulas can be inserted into the rows and columns of the spread-
sheet. The spreadsheet can then be saved in a file for use later.
• Games. Many computer games keep data stored in files. For example, some games
keep a list of player names with their scores stored in a file. These games typically
325
Checkpoint
6.19 Briefly describe what an exception is.
6.20 If an exception is raised and the program does not handle it with a try/except
statement, what happens?
6.21 What type of exception does a program raise when it tries to open a nonexistent
file?
6.22 What type of exception does a program raise when it uses the float function to
convert a non-numeric string to a number?
Review Questions
Multiple Choice
1. A file that data is written to is known as a(n) .
a. input file
b. output file
c. sequential access file
d. binary file
2. A file that data is read from is known as a(n) .
a. input file
b. output file
c. sequential access file
d. binary file
3. Before a file can be used by a program, it must be .
a. formatted
b. encrypted
c. closed
d. opened
5. If a file does not exist and a program attempts to open it in append mode, what
happens?
Algorithm Workbench
1. Write a program that opens an output file with the filename things.txt, writes the
name of an animal, a fruit, and a country to the file on separate lines, then closes the file.
2. Write a program that opens the things.txt file created by the program in Algorithm
Workbench 1, reads all of the data from the file before closing it, and then displays
the data from the file.
3. Write code that does the following: opens an output file with the filename number_
list.txt, uses a loop to write the numbers 1 through 100 to the file, then closes
the file.
4. Write code that does the following: opens the number_list.txt file that was created
by the code you wrote in question 3, reads all of the numbers from the file and displays
them, then closes the file.
5. Modify the code that you wrote in problem 4 so it adds all of the numbers read from
the file and displays their total.
6. Write code that opens an output file with the filename number_list.txt, but does
not erase the file’s contents if it already exists.
7. A file exists on the disk named students.txt. The file contains several records, and
each record contains two fields: (1) the student’s name, and (2) the student’s score
for the final exam. Write code that deletes the record containing “John Perz” as the
student name.
8. A file exists on the disk named students.txt. The file contains several records, and
each record contains two fields: (1) the student’s name, and (2) the student’s score for
the final exam. Write code that changes Julie Milan’s score to 100.
9. What will the following code display?
try:
x = float('abc123')
print('The conversion is complete.')
except IOError:
print('This code caused an IOError.')
except ValueError:
print('This code caused a ValueError.')
print('The end.')
10. What will the following code display?
try:
x = float(abc123)
print(x)
except ValueError:
print('This code caused a ValueError.')
except TypeError:
print('This code caused a TypeError.')
except NameError:
print('This code caused a NameError.')
print('The end.')
Programming Exercises
1. File Display
VideoNote
In this chapter’s source code folder (available on the Premium Companion Website at
File Display www.pearsonglobaleditions.com), you will find a text file named numbers.txt. Write a
program that displays all of the numbers in the file.
2. 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.
3. 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.
4. High Score
In this chapter’s source code folder, you will find a text file named scores.txt. 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.)
5. Sum of Numbers
In this chapter’s source code folder, you will find a text file named numbers.txt. Write a
program that reads all of the numbers stored in the file and calculates their total.
6. Average of Numbers
In this chapter’s source code folder, you will find a text file named numbers.txt. Write a
program that calculates the average of all the numbers stored in the file.
7. Random Number File Writer
Write a program that writes a series of random numbers to a file. Each random number
should be in the range of 1 through 500. The application should let the user specify how
many random numbers the file will hold.
8. 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 called words.txt.
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.