0
0
Pythonprogramming~20 mins

Working with CSV files in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
CSV Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A4
B5
C6
DError: FileNotFoundError
Attempts:
2 left
💡 Hint
Assume 'data.csv' contains 5 rows including the header.
Predict Output
intermediate
2: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})
A
name,age
30,Alice
25,Bob
B
name;age
Alice;30
Bob;25
C
name,age
Alice,30
Bob,25
DError: TypeError
Attempts:
2 left
💡 Hint
DictWriter writes CSV with commas by default and writes header first.
🔧 Debug
advanced
2: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])
AIndexError because some rows have fewer than 3 columns
BFileNotFoundError because 'data.csv' does not exist
CTypeError because csv.reader returns a dict, not a list
DNo error, prints third column of each row
Attempts:
2 left
💡 Hint
Check if all rows have at least 3 columns.
Predict Output
advanced
2: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))
A75
BTypeError
C0
DValueError
Attempts:
2 left
💡 Hint
Assume 'people.csv' has three rows with ages 20, 25, and 30.
🧠 Conceptual
expert
2:00remaining
CSV Dialect and Delimiter Behavior
Which option correctly creates a CSV writer that uses a semicolon (;) as delimiter and quotes all fields?
Acsv.writer(file, delimiter=';', quoting=True)
Bcsv.writer(file, delimiter=';', quotechar='"')
Ccsv.writer(file, delimiter=',', quoting=csv.QUOTE_ALL)
Dcsv.writer(file, delimiter=';', quoting=csv.QUOTE_ALL)
Attempts:
2 left
💡 Hint
Check the parameters for csv.writer regarding delimiter and quoting.