Bird
0
0

Identify the error in this code that writes a CSV file using csv.DictWriter:

medium📝 Debug Q14 of 15
Python - Structured Data Files
Identify the error in this code that writes a CSV file using csv.DictWriter:
import csv
with open('output.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'age'])
    writer.writerow({'name': 'Alice', 'age': 30})
    writer.writerow({'name': 'Bob', 'age': 25})
ADictionaries passed to writerow must have string values only.
BFieldnames list should be a tuple, not a list.
CMissing call to writer.writeheader() before writing rows.
DThe file should be opened in binary mode 'wb'.
Step-by-Step Solution
Solution:
  1. Step 1: Check DictWriter usage

    DictWriter requires calling writeheader() to write the header row before writing data rows.
  2. Step 2: Verify other parts

    Opening file in text mode 'w' is correct in Python 3, fieldnames can be a list, and values can be int or str.
  3. Final Answer:

    Missing call to writer.writeheader() before writing rows. -> Option C
  4. Quick Check:

    Always call writeheader() before writerow() [OK]
Quick Trick: Call writeheader() before writing rows with DictWriter [OK]
Common Mistakes:
  • Forgetting writeheader() call
  • Opening file in binary mode unnecessarily
  • Thinking fieldnames must be tuple
  • Assuming all values must be strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes