You are on page 1of 44

Files and Exception Handling

1
Motivations
Data stored in the program are temporary; they are lost when the
program terminates. To permanently store the data created in a
program, you need to save them in a file on a disk or other
permanent storage. The file can be transported and can be read
later by other programs. There are two types of files: text and
binary. Text files are essentially strings on disk. This chapter
introduces how to read/write data from/to a text file.

When a program runs into a runtime error, the program terminates


abnormally. How can you handle the runtime error so that the
program can continue to run or terminate gracefully? This is the
subject we will introduce in this chapter.

2
Objectives
• To open a file, read/write data from/to a file (§13.2)
• To use file dialogs for opening and saving data (§13.3).
• To develop applications with files (§13.4)
• To read data from a Web resource (§13.5).
• To handle exceptions using the try/except/finally clauses
(§13.6)
• To raise exceptions using the raise statements (§13.7)
• To become familiar with Python’s built-in exception classes
(§13.8)
• To access exception object in the handler (§13.8)
• To define custom exception classes (§13.9)

3
Introduction to File Input and
Output (3 of 4)
• “Reading data from”: process of retrieving
data from a file
• Input file: a file from which data is read
• Three steps when a program uses a file
– Open the file
– Process the file
– Close the file
Types of Files and File Access
Methods
• In general, two types of files
– Text file: contains data that has been encoded as text
– Binary file: contains data that has not been
converted to text
• Two ways to access data stored in file
– Sequential access: file read sequentially from
beginning to end, can’t skip ahead
– Direct access: can jump directly to any piece of data
in the file
Filenames and File Objects (1 of 2)
• Filename extensions: short sequences of
characters that appear at the end of a
filename preceded by a period
– Extension indicates type of data stored in the file
• File object: object associated with a specific
file
– Provides a way for a program to work with the
file: file object referenced by a variable
Filenames and File Objects (2 of 2)

Figure 6-4 A variable name references a file object that is associated with a file

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 6-7
Opening a File
• open function: used to open a file
– Creates a file object and associates it with a file on the
disk
– General format:
– file_object = open(filename,
mode)
• Mode: string specifying how the file will be opened
– Example: reading only ('r'), writing ('w'), and
appending ('a')
Specifying the Location of a File
• If open function receives a filename that does not
contain a path, assumes that file is in same directory as
program
• If program is running and file is created, it is created in
the same directory as the program
– Can specify alternative path and file name in the open
function argument
• Prefix the path string literal with the letter r

• Input = open (“score.txt” , “r”)


• Input = open(r”c:\mydoc\scores.txt”, “r”)
• Input = open(“c:\\mydoc\\scores.txt”, “r”)
Writing Data to a File
• Method: a function that belongs to an object
– Performs operations using that object
• File object’s write method used to write
data to the file
– Format: file_variable.write(string)
• File should be closed using file object close
method
– Format: file_variable.close()
Open a File
How do you write data to a file and read the data back from a file?
You need to create a file object that is associated with a physical
file. This is called opening a file. The syntax for opening a file is as
follows:

file = open(filename, mode)

Mode Description

'r' Open a file for reading only.


'w' Open a file for writing only.
'a' Open a file for appending data. Data are
written to the end of the file.
'rb' Open a file for reading binary data.
'wb' Open a file for writing binary data.
11
Write to a File
outfile = open("test.txt", "w")
outfile.write("Welcome to Python")

WriteDemo

12
Testing File Existence
import os.path
if os.path.isfile("Presidents.txt"):
print("Presidents.txt exists")

13
Reading Data From a File
• read method: file object method that reads
entire file contents into memory
– Only works if file has been opened for reading
– Contents returned as a string
• readline method: file object method that
reads a line from the file
– Line returned as a string, including '\n'
• Read position: marks the location of the next
item to be read from a file
Concatenating a Newline to and
Stripping it From a String
• In most cases, data items written to a file are
values referenced by variables
– Usually necessary to concatenate a '\n' to data
before writing it
• Carried out using the + operator in the argument of the
write method
• In many cases need to remove '\n' from string
after it is read from a file
– rstrip method: string method that strips specific
characters from end of the string
Read from File

file
read([number: int]): str Returns the specified number of characters from the file. If the
argument is omitted, the entire remaining contents are read.
readline(): str Returns the next line of file as a string.
readlines(): list Returns a list of the remaining lines in the file.
write(s: str): None Writes the string to the file.
close(): None Closes the file.

16
Read from a File

After a file is opened for reading data, you can use the
read method to read a specified number of characters or
all characters, the readline() method to read the next line,
and the readlines() method to read all lines into a list.

ReadDemo

17
Appending Data to an Existing File
• When open file with 'w' mode, if the file
already exists it is overwritten
• To append data to a file use the 'a'mode
– If file exists, it is not erased, and if it does not exist
it is created
– Data is written to the file at the end of the current
contents
Append Data to a File

You can use the 'a' mode to open a file for appending data to an
existing file.

AppendDemo

19
Writing and Reading Numeric Data
• Numbers must be converted to strings before
they are written to a file
• str function: converts value to string
• Number are read from a text file as strings
– Must be converted to numeric type in order to
perform mathematical operations
– Use int and float functions to convert string
to numeric value
Writing/Reading Numeric Data

To write numbers, convert them into strings, and then use the write
method to write them to a file. In order to read the numbers back
correctly, you should separate the numbers with a whitespace
character such as ' ', '\n'.

WriteReadNumbers

21
Using Loops to Process Files (1 of 2)
• Files typically used to hold large amounts of data
– Loop typically involved in reading from and writing to
a file
• Often the number of items stored in file is
unknown
– The readline method uses an empty string as a
sentinel when end of file is reached
• Can write a while loop with the condition
while line != ''
Using Loops to Process Files (2 of 2)

Figure 6-17 General logic for detecting the end of a file

Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 6 - 23
Using Python’s for Loop to Read
Lines
• Python allows the programmer to write a for
loop that automatically reads lines in a file and
stops when end of file is reached
– Format: for line in file_object:
– statements
– The loop iterates once over each line in the file
Problem: Counting Each Letter in a File

The problem is to write a program that prompts the


user to enter a file and counts the number of
occurrences of each letter in the file regardless of
case.

CountEachLetter

25
File Dialogs
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename

filenameforReading = askopenfilename()
print("You can read from from " + filenameforReading)

filenameforWriting = asksaveasfilename()
print("You can write data to " + filenameforWriting)

26
File Editor

FileEditor
27
Retrieving Data from the Web
Using Python, you can write simple code to read data from a
Website. All you need to do is to open a URL link using the urlopen
function as follows:

infile = urllib.request.urlopen('http://www.yahoo.com')

import urllib.request
infile = urllib.request.urlopen('http://www.yahoo.com/index.html')
print(infile.read().decode())

CountEachLetterURL

28
Exception Handling
When you run the program in Listing 11.3 or Listing 11.4, what
happens if the user enters a file or an URL that does not exist? The
program would be aborted and raises an error. For example, if you
run Listing 11.3 with an incorrect input, the program reports an IO
error as shown below:

c:\pybook\python CountEachLetter.py
Enter a filename: newinput.txt
Traceback (most recent call last):
File "CountEachLetter.py", line 23, in <module>
main()
File "CountEachLetter.py", line 4, in main
Infile = open(filename, "r"> # Open the file
IOError: [Errno 2] No such file or directory: 'newinput.txt'
29
Exceptions (1 of 4)
• Exception: error that occurs while a program
is running
– Usually causes program to abruptly halt
• Traceback: error message that gives
information regarding line numbers that
caused the exception
– Indicates the type of exception and brief
description of the error that caused exception to
be raised
Exceptions (2 of 4)
• Many exceptions can be prevented by careful
coding
– Example: input validation
– Usually involve a simple decision construct
• Some exceptions cannot be avoided by careful
coding
– Examples
• Trying to convert non-numeric string to an integer
• Trying to open for reading a file that doesn’t exist
Exceptions (3 of 4)
• Exception handler: code that responds when
exceptions are raised and prevents program from
crashing
– In Python, written as try/except statement
• General format: try:
statements
except exceptionName:
statements
• Try suite: statements that can potentially raise an exception
• Handler: statements contained in except block
Exceptions (4 of 4)
• If statement in try suite raises exception:
– Exception specified in except clause:
• Handler immediately following except clause executes
• Continue program after try/except statement
– Other exceptions:
• Program halts with traceback error message

• If no exception is raised, handlers are skipped


The try ... except Clause
try:
<body>
except <ExceptionType>:
<handler>

34
Handling Multiple Exceptions
• Often code in try suite can throw more than
one type of exception
– Need to write except clause for each type of
exception that needs to be handled
• An except clause that does not list a specific
exception will handle any exception that is
raised in the try suite
– Should always be last in a series of except
clauses
Displaying an Exception’s Default
Error Message
• Exception object: object created in memory
when an exception is thrown
– Usually contains default error message pertaining
to the exception
– Can assign the exception object to a variable in an
except clause
• Example: except ValueErroraserr:
– Can pass exception object variable to print
function to display the default error message
The else Clause
• try/except statement may include an
optional else clause, which appears after all
the except clauses
– Aligned with try and except clauses
– Syntax similar to else clause in decision structure
– Else suite: block of statements executed after statements
in try suite, only if no exceptions were raised
• If exception was raised, the else suite is skipped
The finally Clause
• try/except statement may include an
optional finally clause, which appears
after all the except clauses
– Aligned with try and except clauses
– General format: finally:
– statements
– Finally suite: block of statements after the finally
clause
• Execute whether an exception occurs or not
• Purpose is to perform cleanup before exiting
The try ... except Clause
try:
<body>
except <ExceptionType1>:
<handler1>
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else> TestException
finally:
<process_finally>
39
Raising Exceptions
You learned how to write the code to handle exceptions in the
preceding section. Where does an exception come from? How
is an exception created? Exceptions are objects and objects are
created from classes. An exception is raised from a function.
When a function detects an error, it can create an object of an
appropriate exception class and raise the object, using the
following syntax:

raise ExceptionClass("Something is wrong")

RaiseException

40
Processing Exceptions Using Exception
Objects

You can access the exception object in the except


clause.
try
<body>
except ExceptionType as ex:
<handler>
ProcessExceptionObject

41
Binary IO Using Pickling
To perform binary IO using pickling, open a file
using the mode 'rb' or 'wb' for reading binary or
writing binary and invoke pickle module’s dump
and load functions to write and read data.

BinaryIODemo

42
Detecting End of File
If you don’t know how many objects are in the file, how do you
read all the objects? You can repeatedly read an object using the
load function until it throws an EOFError exception. When this
exception is raised, catch it and process it to end the file reading
process.

DetectEndOfFile

43
Case Study: Address Book
Now let us use object IO to create a useful project for
storing and viewing an address book. The user interface of
the program is shown below. The Add button stores a new
address at the end of the file. The First, Next, Previous,
and Last buttons retrieve the first, next, previous, and last
addresses from the file, respectively.

AddressBook

44

You might also like