Chapter 9: Files and Exceptions 1
Files and Exceptions
9.1 Introduction
9.1 Q1: Which of the following statements a), b) or c) is false?
a. Variables, lists, tuples, dictionaries, sets, arrays, pandas Series and pandas
DataFrames offer long-term data storage.
b. Computers store files on secondary storage devices, including solid-state
drives, hard disks and more.
c. Some popular text file formats are plain text, JSON (JavaScript Object Notation)
and CSV (comma-separated values).
d. All of the above statements are true?
9.1 Q2: Which of the following statements a), b) or c) is false?
a. You can use JSON to serialize and deserialize objects to facilitate saving those
objects to secondary storage and transmitting them over the Internet.
b. There are security vulnerabilities to serializing and deserializing data with the
Python Standard Library’s pickle module.
c. The with statement automatically releases a resource at the end of the state-
ment’s suite.
d. All of the above statements are true.
9.2 Files
9.2 Q1: Which of the following statements a), b) or c) is false?
a. Python views text files and binary files (for images, videos and more) as se-
quences of bytes.
b. As in lists and arrays, the first character in a text file and byte in a binary file is
located at position 0, so in a file of n characters or bytes, the highest position num-
ber is n – 1.
c. For each file you open, Python creates a file object that you’ll use to interact
with the file.
d. All of the above statements are true.
4 Chapter 9: Files and Exceptions
a. A file object’s readlines method reads an entire text file and returns each line
as a string in a list of strings.
b. Calling readlines for a large file can be a time-consuming operation, which
must complete before you can begin using the list of strings.
c. Using the file object in a for statement enables your program to process each
text line as it’s read.
d. All of the above statements are true.
9.4 Updating Text Files
No questions.
9.5 Serialization with JSON
9.5 Q1: Which of the following statements are false?
a. Many libraries you’ll use to interact with cloud-based services such as Twitter,
IBM Watson and others communicate with your applications via JSON (JavaScript
Object Notation) objects.
b. JSON is a data-interchange format readable only by computers and used to rep-
resent objects (such as dictionaries, lists and more) as collections of name–value
pairs.
c. JSON can represent objects of custom classes.
d. JSON has become the preferred data format for transmitting objects across
platforms. This is especially true for invoking cloud-based web services, which
are functions and methods that you call over the Internet.
9.5 Q2: Which of the following statements a), b) or c) is false?
a. JSON objects are similar to Python lists. Each JSON object contains a comma-
separated list of property names and values, in curly braces. For example, the fol-
lowing JSON object might represent a client record:
{“account”: 100, “name”: “Jones”, “balance”: 24.98}
b. JSON also supports arrays which, like Python lists, are comma-separated values
in square brackets. For example, the following is an acceptable JSON array of
numbers:
[100, 200, 300]
Chapter 9: Files and Exceptions 5
c. Values in JSON objects and arrays can be strings in double quotes, numbers,
JSON Boolean values (true or false), null (to represent no value, like None in
Python), arrays and other JSON objects.
d. All of the above statements are true.
9.5 Q3: The json module enables you to convert objects to JSON (JavaScript Ob-
ject Notation) text format. This is known as ________ the data.
a. chunking
b. calibrating
c. serializing
d. registering
9.5 Q4: Which of the following statements a), b) or c) is false?
a. The following code writes an object in JSON format to a file:
import json
with open(‘accounts.json‘, ‘w’) as accounts:
json.dump(accounts_dict, accounts)
b. The snippet in Part (a) opens the file accounts.json and uses the json mod-
ule’s dump function to serialize the dictionary accounts_dict into the file.
c. JSON delimits strings with double-quote characters.
d. All of the above statements are true.
9.5 Q5: The json module’s ________ function reads the entire JSON contents of its
file object argument and converts the JSON into a Python object. This is known as
________ the data.
a. read, serializing
b. load, serializing
c. load, deserializing
d. read, deserializing
9.5 Q6: Which of the following statements a), b) or c) is false?
a. The json module’s dumps function returns a Python string representation of
an object in JSON format.
b. Using dumps with load, you can read JSON from a file and display it in a nicely
indented format—sometimes called “pretty printing” the JSON.
c. When the dumps function call includes the indent keyword argument, as in
6 Chapter 9: Files and Exceptions
with open(‘accounts.json‘, ‘r’) as accounts:
print(json.dumps(json.load(accounts), indent=4))
the string contains newline characters and indentation for pretty printing—you
also can use indent with the dump function when writing to a file:
d. All of the above statements are true.
9.6 Focus on Security: pickle Serialization and
Deserialization
9.6 Q1: Which of the following statements a), b) or c) is false?
a. The Python Standard Library’s pickle module can serialize objects into the
data formats of many popular programming languages.
b. Pickle has potential security issues.
c. If you write your own pickling and de-pickling code, pickling can be secure.
d. All of the above statements are true.
9.7 Additional Notes Regarding Files
9.7 Q1: Which of the following statements a), b) or c) is false?
a. The file open modes for writing and appending raise a FileNotFoundError if
the file does not exist.
b. Each text-file mode has a corresponding binary-file mode specified with b, as
in ‘rb’ or ‘wb+’.
c. You use binary-file modes for reading or writing binary files, such as images,
audio, video, compressed ZIP files and many other popular custom file formats.
d. All of the above statements are true.
9.7 Q2: Which of the following statements is false?
a. For a text file, the read method returns a string containing the number of char-
acters specified by the method’s integer argument. For a binary file, the method
returns the specified number of bytes. If no argument is specified, the method
returns the entire contents of the file.
b. The readline method returns one line of text as a string, including the newline
character if there is one.
c. The readline method issues an EndOfFileError when it encounters the end
of the file.
Chapter 9: Files and Exceptions 7
d. The writelines method receives a list of strings and writes its contents to a
file.
9.8 Handling Exceptions
9.8 Q1: Various types of exceptions can occur when you work with files. Which
of the following statements a), b) or c) is false?
a. A FileNotFoundError occurs if you attempt to open a non-existent file for
reading with the ‘r’ or ‘r+’ modes.
b. A PermissionsError occurs if you attempt an operation for which you do not
have permission. This might occur if you try to open a file that your account is not
allowed to access or create a file in a folder where your account does not have
permission to write, such as where your computer’s operating system is stored.
c. A LockedError (with the error message ‘I/O operation on closed file.’)
occurs when you attempt to write to a file that has already been closed.
d. All of the above statements are true.
9.8.1 Division by Zero and Invalid Input
9.8 Q2: Which of the following statements is false?
a. Attempting to divide by 0 results in a ZeroDivisionError.
b. When a program attempts to divide by zero, the interpreter is said to raise an
exception of type ZeroDivisionError.
c. When an exception is raised in an interactive IPython session, it displays the
exception’s traceback, then terminates the IPython session.
d. If an exception occurs in a script, IPython terminates the script and displays the
exception’s traceback.
9.8 Q3: The int function raises a ________ if you attempt to convert to an integer a
string (like ‘hello’) that does not represent a number.
a. NameError
b. ConversionError
c. ValueError
8 Chapter 9: Files and Exceptions
d. None of the above
9.8.2 try Statements
9.8 Q4: The following code uses exception handling to catch and handle any
ValueErrors and ZeroDivisionErrors that arise.
1 while True:
2 try:
3 number1 = int(input(‘Enter numerator: ‘))
4 number2 = int(input(‘Enter denominator: ‘))
5 result = number1 / number2
6 except ValueError:
7 print(‘You must enter two integers\n’)
8 except ZeroDivisionError:
9 print(‘Attempted to divide by zero\n’)
10 else:
11 print(f‘{number1:.3f} / {number2:.3f} = {result:.3f}‘)
12 break
Where in the code could either or both of these errors arise?
a. line 3
b. line 5
c. lines 3 and 4
d. lines 3, 4 and 5
9.8 Q5: Which of the following statements is false?
a. A try clause may be followed by one or more except clauses that immediately
follow the try clause’s suite.
b. The except clauses also are known as exception handlers.
c. Each except clause specifies the type of exception it handles.
d. After the last except clause, an optional else clause specifies code that should
execute only if the code in the try suite raised an exception.
9.8 Q6: Which of the following statements is false?
a. When an exception occurs in a try suite, it terminates immediately.
Chapter 9: Files and Exceptions 9
b. When there are except handlers, program control transfers to the first one
that matches the type of the raised exception. If there are no except handlers
that match the raised exception, a process called stack unwinding occurs.
c. When an except clause successfully handles an exception, program execution
resumes with the finally clause (if there is one), then with the next statement
after the try statement.
d. After an exception is handled, program control returns to the raise point.
9.8.3 Catching Multiple Exceptions in One except Clause
9.8 Q7: Which of the following statements is false?
a. A try clause is often followed by several except clauses to handle various
types of exceptions.
b. When no exceptions occur in the try suite, program execution resumes with
the else clause (if there is one); otherwise, program execution resumes with the
next statement after the try statement.
c. If several except suites are identical, you can catch those exception types by
specifying them as a tuple in a single except handler, as in:
except [type1, type2, …] as variable_name
d. You can use the variable name in the optional as-clause to reference the excep-
tion object in the except suite.
9.8.4 What Exceptions Does a Function or Method Raise?
No questions.
9.8.5 What Code Should Be Placed in a try Suite?
9.8 Q8: Which of the following statements a), b) or c) is false?
a. Wrap a separate try statement around every individual statement that raises
an exception.
b. For proper exception-handling granularity, each try statement should enclose
a section of code small enough that, when an exception occurs, the specific con-
text is known and the except handlers can process the exception properly.
10 Chapter 9: Files and Exceptions
c. If many statements in a try suite raise the same exception types, multiple try
statements may be required to determine each exception’s context.
d. All of the above statements are true.
9.9 finally Clause
9.9 Q1: Which of the following statements a), b) or c) is false?
a. Operating systems typically can prevent more than one program from manip-
ulating a file at once.
b. When a program finishes processing a file, the program immediately should
close it to release the resource. This enables other programs to use the file (if
they’re allowed to access it).
c. Closing a file creates a resource leak in which the file resource is not available
to other programs.
d. All of the above statements are true.
9.9 Q2: Which of the following statements is false?
a. A try statement can have a finally clause as its last clause after any except
clauses or else clause.
b. The finally clause is guaranteed to execute, regardless of whether its try
suite executes successfully or an exception occurs.
c. In other languages that have finally, the finally suite is an ideal location to
place resource-deallocation code for resources acquired in the corresponding
try suite.
d. In Python, we prefer the else clause of a try statement for resource-dealloca-
tion code and place other kinds of “clean up” code in the finally suite.
9.9 Q3: Which of the following statements a), b) or c) is false?
Chapter 9: Files and Exceptions 11
a. When the finally clause terminates, program control continues with the next
statement after the try statement. In an IPython session, the next In [] prompt
appears.
b. The following code includes a try statement in which an exception occurs in
the try suite:
try:
print(‘try suite that raises an exception’)
int(‘hello’)
print(‘this will not execute’)
except ValueError:
print(‘a ValueError occurred’)
else:
print(‘else will not execute because an exception occurred’)
finally:
print(‘finally always executes’)
c. The finally clause executes only when an exception occurs in the correspond-
ing try suite.
d. All of the above statements are true.
9.9 Q4: Which of the following statements a), b) or c) is false?
a. Most resources that require explicit release, such as files, network connections
and database connections, have potential exceptions associated with processing
those resources.
b. A program that processes a file might raise IOErrors. For this reason, robust
file-processing code normally appears in a try suite containing a with statement
to guarantee that the resource gets released.
c. When a with statement is in a try suite, you can catch in except handlers any
exceptions that occur and you do not need a finally clause because the with
statement handles resource deallocation.
d. All of the above statements are true.
9.10 Explicitly Raising an Exception
9.10 Q1: Which of the following statements is false?
a. The simplest form of the raise statement is
raise ExceptionClassName
b. In most cases, when you need to raise an exception, it’s recommended that you
customize the exception type with a meaningful exception name.
12 Chapter 9: Files and Exceptions
c. The raise statement creates an object of the specified exception class. Option-
ally, the exception class name may be followed by parentheses containing argu-
ments to initialize the exception object—typically to provide a custom error mes-
sage string.
d. Code that raises an exception first should release any resources acquired be-
fore the exception occurred.
9.11 (Optional) Stack Unwinding and Tracebacks
9.11 Q1: Which of the following statements a), b) or c) is false?
a. Each exception object stores information indicating the precise series of func-
tion calls that led to the exception. This is helpful when debugging your code.
b. In the following function definitions, function1 calls function2 and func-
tion2 raises an Exception:
def function1():
function2()
def function2():
raise Exception(‘An exception occurred’)
c. In an interactive IPython session, calling function1 in Part (b) results in the
following traceback:
——————————————————————–
Exception Traceback (most recent call last)
<ipython-input-3-c0b3cafe2087> in <module>()
—-> 1 function1()
<ipython-input-1-a9f4faeeeb0c> in function1()
1 def function1():
—-> 2 function2()
3
<ipython-input-2-c65e19d6b45b> in function2()
1 def function2():
—-> 2 raise Exception(‘An exception occurred’)
Exception: An exception occurred
d. All of the above statements are true.
9.11 Q2: Which of the following statements is false?
Chapter 9: Files and Exceptions 13
a. A traceback shows the type of exception that occurred followed by the complete
function-call stack that led to the raise point. The stack’s ________ function call is
listed ________ and the ________ is ________, so the interpreter displays the following
text as a reminder:
Traceback (most recent call last)
a. bottom, first, top, last.
b. bottom, last, top, first
c. top, first, bottom, last
d. top, last, bottom, first
9.11 Q3: Which of the following statements is false?
a. Raising an exception in a finally suite can lead to subtle, hard-to-find prob-
lems.
b. If an exception occurs and is not processed by the time the finally suite exe-
cutes, stack unwinding occurs.
c. If the finally suite raises a new exception that the suite does not catch, pro-
gram execution terminates.
d. A finally suite should always enclose in a try statement any code that may
raise an exception, so that the exceptions will be processed within that suite.
9.12 Intro to Data Science: Working with CSV Files
9.12.1 Python Standard Library Module csv
9.12 Q1: Which of the following statements is false?
a. The csv module provides functions for working with CSV files. Many other Py–
thon libraries also have built-in CSV support.
b. The csv module’s documentation recommends opening CSV files with the ad-
ditional keyword argument newline=” to ensure that newlines are processed
properly.
c. The csv module’s writer function returns an object that writes CSV data to the
specified file object.
d. CSV files cannot contain spaces after commas.
Chapter 9: Files and Exceptions 15
b. To save space, we can view the first five and last five rows with DataFrame
methods head and tail. Both methods return five rows by default, but you can
specify the number of rows to display as an argument.
c. Pandas adjusts each column’s width, based on the widest value in the column.
d. If the value in a column of a row is NaN (not a number) that indicates a missing
value in the dataset.
9.12.4 Simple Data Analysis with the Titanic Disaster Dataset
No questions.
9.12.5 Titanic Passenger Age Histogram
9.12 Q5: Which of the following statements is false?
a. When you call describe on a DataFrame containing both numeric and non-
numeric columns, describe calculates the statistics below only for the numeric
columns—in the Titanic dataset, for example, just the age column (the dataset ‘s
only numeric column):
age
count 1046.00
mean 29.88
std 14.41
min 0.17
25% 21.00
50% 28.00
75% 39.00
max 80.00
b. When performing calculations, Pandas ignores missing data (NaN) by default.
c. For non-numeric data, describe displays different descriptive statistics, such
as unique (the number of unique values in the result), top (the most frequently
occurring value in the result) and freq (the number of occurrences of the top
value).
d. A DataFrame’s hist method automatically analyzes each column’s data, and
produces a corresponding histogram for each.