Challenge - 5 Problems
CSV Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Reading CSV and counting rows
What is the output of this code that reads a CSV file and counts its rows?
Python
import csv with open('data.csv', newline='') as csvfile: reader = csv.reader(csvfile) count = 0 for row in reader: count += 1 print(count)
Attempts:
2 left
💡 Hint
Assume 'data.csv' contains 5 rows including the header.
✗ Incorrect
The code counts all rows including the header. If the file has 5 rows total, the output is 5.
❓ Predict Output
intermediate2:00remaining
Writing CSV with DictWriter
What will be the content of 'output.csv' after running this code?
Python
import csv with open('output.csv', 'w', newline='') as csvfile: fieldnames = ['name', 'age'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'name': 'Alice', 'age': 30}) writer.writerow({'name': 'Bob', 'age': 25})
Attempts:
2 left
💡 Hint
DictWriter writes CSV with commas by default and writes header first.
✗ Incorrect
The DictWriter writes the header and rows with commas separating fields in the order of fieldnames.
🔧 Debug
advanced2:00remaining
Fix the error in CSV reading code
This code tries to read a CSV file but raises an error. What is the cause?
Python
import csv with open('data.csv') as f: reader = csv.reader(f) for row in reader: print(row[2])
Attempts:
2 left
💡 Hint
Check if all rows have at least 3 columns.
✗ Incorrect
If any row has fewer than 3 columns, accessing row[2] causes IndexError.
❓ Predict Output
advanced2:00remaining
Using csv.DictReader to access data
What is the output of this code snippet?
Python
import csv with open('people.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) ages = [int(row['age']) for row in reader] print(sum(ages))
Attempts:
2 left
💡 Hint
Assume 'people.csv' has three rows with ages 20, 25, and 30.
✗ Incorrect
The code sums the ages 20 + 25 + 30 = 75.
🧠 Conceptual
expert2:00remaining
CSV Dialect and Delimiter Behavior
Which option correctly creates a CSV writer that uses a semicolon (;) as delimiter and quotes all fields?
Attempts:
2 left
💡 Hint
Check the parameters for csv.writer regarding delimiter and quoting.
✗ Incorrect
Option D correctly sets delimiter to ';' and quoting to csv.QUOTE_ALL to quote all fields.