0% found this document useful (0 votes)
6 views7 pages

Chapter 6 Files Exceptions

Chapter 6 discusses file input and output, explaining how programs can save data in files for later use, as opposed to losing data when the program stops. It also covers exception handling, detailing what happens when exceptions are not handled and how to manage various types of exceptions in Python. The chapter includes review questions and programming exercises to reinforce the concepts of file processing and exception management.

Uploaded by

uphetheniphofu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

Chapter 6 Files Exceptions

Chapter 6 discusses file input and output, explaining how programs can save data in files for later use, as opposed to losing data when the program stops. It also covers exception handling, detailing what happens when exceptions are not handled and how to manage various types of exceptions in Python. The chapter includes review questions and programming exercises to reinforce the concepts of file processing and exception management.

Uploaded by

uphetheniphofu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

CHAPTER

6 Files and Exceptions

TOPICS
6.1 Introduction to File Input and Output 6.3 Processing Records
6.2 Using Loops to Process Files 6.4 Exceptions

6.1 Introduction to File Input and Output

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

M06_GADD8637_05_GE_C06.indd 325 28/04/2021 19:25


376 Chapter 6   Files and Exceptions

What If an Exception Is Not Handled?


Unless an exception is handled, it will cause the program to halt. There are two possible
ways for a thrown exception to go unhandled. The first possibility is for the try/except
statement to contain no except clauses specifying an exception of the right type. The sec-
ond possibility is for the exception to be raised from outside a try suite. In either case, the
exception will cause the program to halt.
In this section, you’ve seen examples of programs that can raise ZeroDivisionError
exceptions, IOError exceptions, and ValueError exceptions. There are many different
types of exceptions that can occur in a Python program. When you are designing try/
except statements, one way you can learn about the exceptions that you need to handle
is to consult the Python documentation. It gives detailed information about each possible
exception and the types of errors that can cause them to occur.
Another way that you can learn about the exceptions that can occur in a program is through
experimentation. You can run a program and deliberately perform actions that will cause
errors. By watching the traceback error messages that are displayed, you will see the names of
the exceptions that are raised. You can then write except clauses to handle these exceptions.

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

M06_GADD8637_05_GE_C06.indd 376 28/04/2021 19:25


Review Questions 377

4. When a program is finished using a file, it should do this.


a. erase the file
b. open the file
c. close the file
d. encrypt the file
5. The contents of this type of file can be viewed in an editor such as Notepad.
a. text file
b. binary file
c. English file
d. human-readable file
6. This type of file contains data that has not been converted to text.
a. text file
b. binary file
c. Unicode file
d. symbolic file
7. When working with this type of file, you access its data from the beginning of the file
to the end of the file.
a. ordered access
b. binary access
c. direct access
d. sequential access
8. When working with this type of file, you can jump directly to any piece of data in the
file without reading the data that comes before it.
a. ordered access
b. binary access
c. direct access
d. sequential access
9. This is a small “holding section” in memory that many systems write data to before
writing the data to a file.
a. buffer
b. variable
c. virtual file
d. temporary file
10. This marks the location of the next item that will be read from a file.
a. input position
b. delimiter
c. pointer
d. read position
11. When a file is opened in this mode, data will be written at the end of the file’s existing
contents.
a. output mode
b. append mode
c. backup mode
d. read-only mode

M06_GADD8637_05_GE_C06.indd 377 28/04/2021 19:25


378 Chapter 6   Files and Exceptions

12. This is a single piece of data within a record.


a. field
b. variable
c. delimiter
d. subrecord
13. When an exception is generated, it is said to have been __________.
a. built
b. raised
c. caught
d. killed
14. This is a section of code that gracefully responds to exceptions.
a. exception generator
b. exception manipulator
c. exception handler
d. exception monitor
15. You write this statement to respond to exceptions.
a. run/handle
b. try/except
c. try/handle
d. attempt/except
True or False
1. When working with a sequential access file, you can jump directly to any piece of data
in the file without reading the data that comes before it.
2. When you open a file that file already exists on the disk using the 'w' mode, the con-
tents of the existing file will be erased.
3. The process of opening a file is only necessary with input files. Output files are auto-
matically opened when data is written to them.
4. When an input file is opened, its read position is initially set to the first item in the file.
5. When a file that already exists is opened in append mode, the file’s existing contents
are erased.
6. If you do not handle an exception, it is ignored by the Python interpreter, and the
program continues to execute.
7. You can have more than one except clause in a try/except statement.
8. The else suite in a try/except statement executes only if a statement in the try suite
raises an exception.
9. The finally suite in a try/except statement executes only if no exceptions are raised
by statements in the try suite.
Short Answer
1. Describe the three steps that must be taken when a file is used by a program.
2. Why should a program close a file when it’s finished using it?
3. What is a file’s read position? Where is the read position when a file is first opened
for reading?
4. In which mode should a file be opened to allow data to be written to it, erasing any
previous data?

M06_GADD8637_05_GE_C06.indd 378 28/04/2021 19:25


Review Questions 379

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.')

M06_GADD8637_05_GE_C06.indd 379 28/04/2021 19:25


380 Chapter 6   Files and Exceptions

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.

M06_GADD8637_05_GE_C06.indd 380 28/04/2021 19:25


Programming Exercises 381

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 golf.txt. (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 golf.txt file and displays them.
11. Personal Web Page Generator
Write a program that asks the user for his or her name, then asks the user to enter a sen-
tence that describes himself or herself. Here is an example of the program’s screen:
Enter your name: Julie Taylor Enter
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. Enter
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>

12. Average Steps Taken


A Personal Fitness Tracker is a wearable device that tracks your physical activity, calories
burned, heart rate, sleeping patterns, and so on. One common physical activity that most
of these devices track is the number of steps you take each day.
If you have downloaded this book’s source code from the Premium Companion Website,
you will find a file named steps.txt in the Chapter 06 folder. (The Premium Companion
Website can be found at www.pearsonglobaleditions.com.) The steps.txt file contains
the number of steps a person has taken each day for a year. There are 365 lines in the
file, and each line contains the number of steps taken during a day. (The first line is the
number of steps taken on January 1st, the second line is the number of steps taken on
January 2nd, and so forth.) Write a program that reads the file, then displays the average
number of steps taken for each month. (The data is from a year that was not a leap year,
so February has 28 days.)

M06_GADD8637_05_GE_C06.indd 381 28/04/2021 19:25

You might also like