Bird
0
0

What is the issue with this code snippet?

medium📝 Debug Q6 of 15
Python - Structured Data Files
What is the issue with this code snippet?
import csv
with open('data.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'age'])
    writer.writerow({'name': 'John', 'age': 28})
    writer.writeheader()
Awriteheader() should be called before writing rows
BMissing import statement for csv module
CThe file should be opened in read mode
Dfieldnames list is missing required columns
Step-by-Step Solution
Solution:
  1. Step 1: Check order of method calls

    writeheader() writes the header row and should be called before any writerow() calls.
  2. Step 2: Identify the error

    In the snippet, writerow() is called before writeheader(), so the header is missing or misplaced.
  3. Final Answer:

    writeheader() should be called before writing rows -> Option A
  4. Quick Check:

    Header must be written before rows [OK]
Quick Trick: Call writeheader() before writerow() [OK]
Common Mistakes:
  • Calling writeheader() after writing rows
  • Forgetting to specify fieldnames
  • Not using newline='' when opening file

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes