Every problem in the chapter beside the book’s answer, a chapter at a time as you scroll.

Chapter 14: Files

28 problems · 0 figures

Concepts in Practice 14.1.1 §14.1 source ↗

What is the correct way to open a file named firstfile.txt so that the file's contents can be read into a Python program?
  1. a.
    open("firstfile")
  2. b.
    open("firstfile.txt")
  3. c.
    fileobj = open("firstfile.txt")

Answer

C. fileobj = open("firstfile.txt")
The file is opened and is associated with the fileobj object. Reading from the file will be possible using fileobj.

Concepts in Practice 14.1.2 §14.1 source ↗

Suppose that there is no file named input.txt. What is the result of trying to execute open("input.txt")?
  1. a.
    Error
  2. b.
    nothing
  3. c.
    "input.txt" file is created.

Answer

A. Error
The file must exist in the same folder as the Python file in order for the file to be opened.

Concepts in Practice 14.1.3 §14.1 source ↗

What is the result of the following code?
fileobj = open("newfile.txt")
print(fileobj)
  1. a.
    Error
  2. b.
    Information about the object fileobj is printed.
  3. c.
    The contents of newfile.txt are printed.

Answer

B. Information about the object fileobj is printed.
Python interprets this command as the programmer trying to print the object details. The object details are printed. Ex: <_io.TextIOWrapper name='newfile.txt' mode='r' encoding='cp1252'>.

Concepts in Practice 14.1.4 §14.1 source ↗

Suppose fileobj = open("input.txt") has already been executed for each question below.

input.txt:

Hello world!
How are you?
What is the correct way to use the read() function to read the contents of input.txt into a string file_str?
  1. a.
    file_str = read(fileobj)
  2. b.
    file_str = read("input.txt")
  3. c.
    file_str = fileobj.read()

Answer

C. file_str = fileobj.read()
The read() function is called on fileobj. The file's contents will be read into file_str.

Concepts in Practice 14.1.5 §14.1 source ↗

Suppose fileobj = open("input.txt") has already been executed for each question below.

input.txt:

Hello world!
How are you?
What is the correct way to use the readlines() function?
  1. a.
    file_lines = readlines(fileobj)
  2. b.
    file_lines = fileobj.readlines()

Answer

B. file_lines = fileobj.readlines()
The readlines() function is called on fileobj. file_lines is the string list ['Hello world!\n', 'How are you?\n'].

Concepts in Practice 14.1.6 §14.1 source ↗

Suppose fileobj = open("input.txt") has already been executed for each question below.

input.txt:

Hello world!
How are you?
What is printed as a result of executing print(fileobj.readline())?
  1. a.
    The first line of input.txt is printed.
  2. b.
    The contents of the file input.txt are printed.
  3. c.
    Error

Answer

A. The first line of input.txt is printed.
The readline() function reads the next line of a file. Since readline() is called right after opening the file the first line is read. The resulting string "Hello world!" is printed. Note that readline() includes the '\n' character so the print will include an additional newline.

Concepts in Practice 14.2.1 §14.2 source ↗

Assume that a file named logfile.txt exists.

To read logfile.txt, which of the following lines of code works best?
  1. a.
    logfile = open("logfile.txt")
  2. b.
    logfile = open("logfile.txt", 'w')
  3. c.
    logfile = open("logfile.txt", 'a')

Answer

A. logfile = open("logfile.txt")
The default mode for the open() function is read.

Concepts in Practice 14.2.2 §14.2 source ↗

Assume that a file named logfile.txt exists.

Additions are to be made to logfile.txt. Which of the following lines of code works best?
  1. a.
    infile = open("logfile.txt")
  2. b.
    infile = open("logfile.txt", 'w')
  3. c.
    infile = open("logfile.txt", 'a')

Answer

C. infile = open("logfile.txt", 'a')
'a' indicates append mode allowing additions to the file.

Concepts in Practice 14.2.3 §14.2 source ↗

Assume that a file named logfile.txt exists.

A new file called newlog.txt must be created. Which of the following lines of code works best?
  1. a.
    logfile = open("newlog.txt")
  2. b.
    logfile = open("newlog.txt", 'w')
  3. c.
    logfile = open("newlog.txt", 'a')

Answer

B. logfile = open("newlog.txt", 'w')
'w' indicates write mode, and newlog.txt will be created or overwritten (if newlog.txt already exists) and will allow writing.

Concepts in Practice 14.2.4 §14.2 source ↗

resources.txt already exists. What would happen for each of the following snippets of code?

outfile = open("resources.txt", 'w')
outfile.write("new content")
  1. a.
    nothing
  2. b.
    The contents of the resources.txt file is overwritten with the line "new content".
  3. c.
    The resources.txt file is overwritten, but the contents of resources.txt are uncertain.

Answer

C. The resources.txt file is overwritten, but the contents of resources.txt are uncertain.
resources.txt is likely empty, but the state of resources.txt is uncertain. To ensure the contents are saved correctly, the close() function must be used.

Concepts in Practice 14.2.5 §14.2 source ↗

resources.txt already exists. What would happen for each of the following snippets of code?

outfile = open("resources.txt", 'w')
outfile.write("new content")
outfile.close()
  1. a.
    The content of the resources.txt file is overwritten with the line "new content".
  2. b.
    The line "new content" is added to the end of resources.txt.

Answer

A. The content of the resources.txt file is overwritten with the line "new content".
Write mode will overwrite the existing file. The close() statement finalizes changes to the file.

Concepts in Practice 14.2.6 §14.2 source ↗

resources.txt already exists. What would happen for each of the following snippets of code?

outfile = open("resources.txt", 'a')
outfile.write("new content")
outfile.close()
  1. a.
    The content of the resources.txt file is overwritten with the line "new content".
  2. b.
    The line "new content" is added to the end of resources.txt.

Answer

B. The line "new content" is added to the end of resources.txt.
Append mode adds to the existing file. resources.txt is opened such that additions can be made to the file.

Concepts in Practice 14.3.1 §14.3 source ↗

For each question, assume that the Python file executing the open() function is not in the same folder as the out.txt file.

Each question indicates the location of out.txt, the type of computer, and the desired mode for opening the file. Choose which option is best for opening out.txt.

/users/turtle/files on a Mac for reading
  1. a.
    fileobj = open("out.txt")
  2. b.
    fileobj = open("/users/turtle/files/out.txt")
  3. c.
    fileobj = open("/users/turtle/files/out.txt", 'w')

Answer

B. fileobj = open("/users/turtle/files/out.txt")
The path followed by the filename enables the file to be opened correctly and in read mode by default.

Concepts in Practice 14.3.2 §14.3 source ↗

For each question, assume that the Python file executing the open() function is not in the same folder as the out.txt file.

Each question indicates the location of out.txt, the type of computer, and the desired mode for opening the file. Choose which option is best for opening out.txt.

c:\documents\ on a Windows computer for reading
  1. a.
    fileobj = open("out.txt")
  2. b.
    fileobj = open("c:/documents/out.txt", 'a')
  3. c.
    fileobj = open("c:/documents/out.txt")

Answer

C. fileobj = open("c:/documents/out.txt")
The use of forward slashes / replacing the Windows standard backslashes \ enables the path to be read correctly. The path followed by the filename enables the file to be opened and when reading a file read mode is preferable.

Concepts in Practice 14.3.3 §14.3 source ↗

For each question, assume that the Python file executing the open() function is not in the same folder as the out.txt file.

Each question indicates the location of out.txt, the type of computer, and the desired mode for opening the file. Choose which option is best for opening out.txt.

/users/turtle/logs on a Linux computer for writing
  1. a.
    fileobj = open("out.txt")
  2. b.
    fileobj = open("/users/turtle/logs/out.txt")
  3. c.
    fileobj = open("/users/turtle/logs/out.txt", 'w')

Answer

C. fileobj = open("/users/turtle/logs/out.txt", 'w')
The file is created or overwritten and changes can be written into the file.

Concepts in Practice 14.3.4 §14.3 source ↗

For each question, assume that the Python file executing the open() function is not in the same folder as the out.txt file.

Each question indicates the location of out.txt, the type of computer, and the desired mode for opening the file. Choose which option is best for opening out.txt.

c:\proj\assets on a Windows computer in append mode
  1. a.
    fileobj = open("c:\\proj\\assets\\out.txt", 'a')
  2. b.
    fileobj = open("c:\proj\assets\out.txt", 'a')

Answer

A. fileobj = open("c:\\proj\\assets\\out.txt", 'a')
Since the backslashes in the Windows path appear in the string argument, which usually tells Python that this is part of an escape sequence, the backslashes must be ignored using an additional backslash \ character.

Concepts in Practice 14.3.5 §14.3 source ↗

Why does readlines() work for reading the rows in a CSV file?
  1. a.
    readlines() reads line by line using the newline \n character.
  2. b.
    readlines() is not appropriate for reading a CSV file.
  3. c.
    readlines() automatically recognizes a CSV file and works accordingly.

Answer

A. readlines() reads line by line using the newline \n character.
The newline \n character indicates where line breaks are in a file and is used by the readlines() function to tell lines apart.

Concepts in Practice 14.3.6 §14.3 source ↗

For the code in the example, what would be the output for the statement print(list_csv[1][2])?
  1. a.
    532
  2. b.
    268
  3. c.
    Jane Eyre

Answer

B. 268
The cell at the 2nd row and 3rd column contains '268' .

Concepts in Practice 14.3.7 §14.3 source ↗

What is the output of the following code for the books.csv seen above?
file_obj = open("books.csv")

csv_read = file_obj.readline()

print(csv_read)
  1. a.
    ['Title, Author, Pages\n', '1984, George Orwell, 268\n', 'Jane Eyre, Charlotte Bronte, 532\n', 'Walden, Henry David Thoreau, 156\n', 'Moby Dick, Herman Melville, 538']
  2. b.
    [['Title', ' Author', ' Pages'], ['1984', ' George Orwell', ' 268'], ['Jane Eyre', ' Charlotte Bronte', ' 532'], ['Walden', ' Henry David Thoreau', ' 156'], ['Moby Dick', ' Herman Melville', ' 538']]
  3. c.
    Title, Author, Pages

Answer

C. Title, Author, Pages
The first line of the books.csv is read into csv_read. The first line is 'Title, Author, Pages' , which is the same as the first row.

Concepts in Practice 14.4.1 §14.4 source ↗

What error might occur in each situation?

The line "soft drinks" is changed to "3-4 soft drinks".
  1. a.
    FileNotFoundError
  2. b.
    IndexError
  3. c.
    ValueError

Answer

C. ValueError
The string "3-4" is not an integer, so the int() function raises a ValueError like before.

Concepts in Practice 14.4.2 §14.4 source ↗

What error might occur in each situation?

for line in open("food_order.text"):
  1. a.
    FileNotFoundError
  2. b.
    IndexError
  3. c.
    ValueError

Answer

A. FileNotFoundError
The filename should end with .txt, not .text.

Concepts in Practice 14.4.3 §14.4 source ↗

What error might occur in each situation?

parts = line.split()
qty = parts[0]
item = parts[1]
  1. a.
    FileNotFoundError
  2. b.
    IndexError
  3. c.
    ValueError

Answer

B. IndexError
If the line has no spaces, then len(parts) will be only 1, and parts[1] will be out of range.

Concepts in Practice 14.4.4 §14.4 source ↗

For each code snippet, what is the output?

word = "one"
try:
  number = int(word)
  print(word, "equals", number)
except ValueError:
  print(word, "is not a number")
  1. a.
    one equals 1
  2. b.
    one is not a number
  3. c.
    ValueError: invalid literal for int() with base 10: 'one'

Answer

B. one is not a number
The int() function raises a ValueError when trying to convert "one" to an integer, so the program jumps to the except clause.

Concepts in Practice 14.4.5 §14.4 source ↗

For each code snippet, what is the output?

word = "one"
try:
  number = int(word)
  print(word, "equals", number)
except IndexError:
  print(word, "is not a number")
  1. a.
    one equals 1
  2. b.
    one is not a number
  3. c.
    ValueError: invalid literal for int() with base 10: 'one'

Answer

C. ValueError: invalid literal for int() with base 10: 'one'
The program crashes and displays this error because the except clause does not handle ValueError.

Concepts in Practice 14.4.6 §14.4 source ↗

For each code snippet, what is the output?

word = "one"
try:
  char = word[3]
  print("The char is", char)
except:
  print("That didn't work")
  1. a.
    The char is e
  2. b.
    That didn't work
  3. c.
    IndexError: string index out of range

Answer

B. That didn't work
If an except clause does not specify a specific error type, then any error type is handled.

Concepts in Practice 14.5.1 §14.5 source ↗

For each code snippet, what is the output?

p3 = Pizza("M")
print(p3)
  1. a.
    Medium pizza for $7.99
  2. b.
    ValueError: Unknown size 'M'
  3. c.
    TypeError: missing argument

Answer

A. Medium pizza for $7.99
"M" is a valid size, so the Pizza object is constructed.

Concepts in Practice 14.5.2 §14.5 source ↗

For each code snippet, what is the output?

raise PizzaError("Invalid size")
  1. a.
    Invalid size
  2. b.
    PizzaError: Invalid size
  3. c.
    NameError: name 'PizzaError' is not defined

Answer

C. NameError: name 'PizzaError' is not defined
PizzaError is not a built-in exception type.

Concepts in Practice 14.5.3 §14.5 source ↗

For each code snippet, what is the output?

raise ValueError
  1. a.
    ValueError
  2. b.
    NameError: name 'ValueError' is not defined
  3. c.
    SyntaxError: Missing parenthesis in call to 'ValueError'

Answer

A. ValueError
An exception can be raised without providing an error message. In this case, the error message is empty, but the exception name is still printed.

Loading chapter 15…

Problems and answers are adapted from Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield and Narges Norouzi, OpenStax, and are used under the CC BY-NC-SA 4.0 licence. Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction. Illustrations: Copyright Rice University, OpenStax, under CC BY-NC-SA 4.0 license. This adaptation is released under the same licence, is non-commercial, and is neither affiliated with nor endorsed by OpenStax or Rice University.