This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python CSV Files, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does csv.DictReader return for each row?
Answer: A dictionary keyed by the header
Why: The first row supplies field names, and each later row becomes a mapping.
What does writer.writerow do?
Answer: Writes one row and a line terminator
Why: Each call writes one record to the output stream.
What does quoting=csv.QUOTE_ALL do?
Answer: Quotes every field
Why: QUOTE_ALL wraps every field in quotes, even when it does not contain a delimiter.
What does this code print?
import csv
from io import StringIO
rows = list(csv.reader(StringIO("a,b\n1,2\n")))
print(rows[1][1])Answer: 2
Why: The second row is ['1', '2'], so index 1 is the string 2.
Complete the module import.
import ____
from io import StringIOAnswer: csv
Why: The csv module provides readers and writers.
Complete the reader that uses header names.
import csv
from io import StringIO
rows = list(csv.____(StringIO("name,score\nAda,92\n")))Answer: DictReader
Why: DictReader maps each row to a dictionary.
Complete the method that writes one row.
import csv
from io import StringIO
buffer = StringIO()
writer = csv.writer(buffer)
writer.____(["a", "b"])Answer: writerow
Why: writerow writes a single record.
Complete the quoting mode that quotes every field.
import csv
from io import StringIO
buffer = StringIO()
writer = csv.writer(buffer, quoting=csv.____)Answer: QUOTE_ALL
Why: QUOTE_ALL is the all-fields quoting constant.
What does the program output?
import csv
from io import StringIO
print(next(csv.reader(StringIO("a,b\n1,2\n"))))Answer: ['a', 'b']
Why: The first row is the list of two header strings.
What appears on the screen?
import csv
from io import StringIO
rows = list(csv.DictReader(StringIO("name,score\nAda,92\n")))
print(rows[0]["score"])Answer: 92
Why: The score field for Ada is the string 92.
What is printed?
import csv
from io import StringIO
buffer = StringIO()
writer = csv.writer(buffer, quoting=csv.QUOTE_ALL)
writer.writerow(["a,b", "c"])
print(buffer.getvalue().strip())Answer: "a,b","c"
Why: QUOTE_ALL wraps both fields, including the one with a comma.
What is the output?
import csv
from io import StringIO
buffer = StringIO()
writer = csv.writer(buffer)
writer.writerow(["a", "b"])
print(buffer.getvalue().strip())Answer: a,b
Why: writerow writes the two fields separated by a comma.
Try the questions first
Open the practice page for Python CSV Files and answer the same 12 questions with instant feedback.