Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q6 of 15
Python - Structured Data Files
Identify the error in this code snippet:
import csv
with open('data.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Bob', 25])
Awriterow() requires strings only, 25 should be '25'
BMissing newline='' in open() causes extra blank lines
CUsing 'w' mode instead of 'a' mode causes overwrite
Dcsv module not imported correctly
Step-by-Step Solution
Solution:
  1. Step 1: Check file open parameters for writing CSV

    On Windows, not specifying newline='' when opening a file for CSV writing causes extra blank lines.
  2. Step 2: Validate other options

    Using 'w' mode is correct for writing new files, writerow() accepts integers, and csv is imported correctly.
  3. Final Answer:

    Missing newline='' in open() causes extra blank lines -> Option B
  4. Quick Check:

    Always use newline='' when writing CSV files [OK]
Quick Trick: Always add newline='' when opening CSV files for writing [OK]
Common Mistakes:
  • Ignoring newline='' causing blank lines
  • Thinking writerow() needs only strings
  • Confusing write mode with append mode

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes