Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q6 of Q15
Python - Structured Data Files
Identify the error in this code snippet:
import csv
with open('data.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Bob', 25])

with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
AUsing csv.reader instead of csv.writer for writing
BFile opened in 'r' mode for writing
CMissing newline='' in open() when writing CSV
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check file open parameters for writing CSV

    When writing CSV files on Windows, missing newline='' causes extra blank lines.
  2. Step 2: Identify missing newline argument

    The code opens file without newline='', which can cause formatting issues.
  3. Final Answer:

    Missing newline='' in open() when writing CSV -> Option C
  4. Quick Check:

    Use newline='' when writing CSV files [OK]
Quick Trick: Always use newline='' when writing CSV files [OK]
Common Mistakes:
MISTAKES
  • Forgetting newline='' causes blank lines
  • Confusing read and write modes
  • Using wrong csv function for task

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes