Bird
Raised Fist0

Which of the following is the correct syntax to open a CSV file for writing with csv.DictWriter?

easy📝 Syntax Q3 of Q15
Python - Structured Data Files
Which of the following is the correct syntax to open a CSV file for writing with csv.DictWriter?
Aopen('file.csv', 'w') as f: writer = csv.DictWriter(f, delimiter=',')
Bwith open('file.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=fields)
Cwith open('file.csv', 'r') as f: writer = csv.DictWriter(f, fieldnames=fields)
Dwith open('file.csv', 'wb') as f: writer = csv.DictWriter(f, fieldnames=fields)
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct file mode for writing text CSV

    Use mode 'w' with newline='' to avoid extra blank lines on Windows.
  2. Step 2: Confirm correct syntax for context manager and DictWriter

    Using with open(...) and passing fieldnames is correct.
  3. Final Answer:

    with open('file.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=fields) -> Option B
  4. Quick Check:

    Open file with 'w' and newline='' for DictWriter [OK]
Quick Trick: Always use newline='' when opening CSV for writing [OK]
Common Mistakes:
MISTAKES
  • Using 'r' mode for writing
  • Forgetting newline='' causing blank lines
  • Using binary mode 'wb' for text CSV

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes