0
0
Pythonprogramming~10 mins

Reading and writing CSV data in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a CSV file for reading.

Python
import csv

with open('data.csv', [1]) as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Drag options to blanks, or click blank then click option'
A'a'
B'w'
C'r'
D'x'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' which opens the file for writing and erases content.
Using 'a' which opens the file for appending, not reading.
2fill in blank
medium

Complete the code to write rows to a CSV file.

Python
import csv

with open('output.csv', 'w', newline=[1]) as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', 30])
Drag options to blanks, or click blank then click option'
A''
BTrue
CNone
D'\n'
Attempts:
3 left
💡 Hint
Common Mistakes
Setting newline to True which is invalid.
Using '\n' as a string which causes errors.
3fill in blank
hard

Fix the error in the code to read CSV data as dictionaries.

Python
import csv

with open('data.csv', 'r') as file:
    reader = csv.DictReader(file)
    for row in [1]:
        print(row['Name'])
Drag options to blanks, or click blank then click option'
Afile
Breader
Ccsv
DDictReader
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to loop over 'file' which is the file object, not the CSV reader.
Using 'csv' or 'DictReader' which are modules or classes, not iterators.
4fill in blank
hard

Fill both blanks to create a dictionary from CSV rows where age is over 25.

Python
import csv

with open('people.csv', 'r') as file:
    reader = csv.DictReader(file)
    result = {row[[1]]: int(row[[2]]) for row in reader if int(row['Age']) > 25}
print(result)
Drag options to blanks, or click blank then click option'
A'Name'
B'Age'
C'City'
D'Country'
Attempts:
3 left
💡 Hint
Common Mistakes
Using fields that don't exist or are not relevant like 'City' or 'Country'.
Not converting age to int causing type errors.
5fill in blank
hard

Fill all three blanks to write a CSV file with headers and two rows.

Python
import csv

with open('newfile.csv', [1], newline=[2]) as file:
    writer = csv.[3](file)
    writer.writerow(['Product', 'Price'])
    writer.writerow(['Book', 12.99])
    writer.writerow(['Pen', 1.5])
Drag options to blanks, or click blank then click option'
A'w'
B''
Cwriter
Dwriterow
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong file mode like 'r' when writing.
Not setting newline properly causing extra blank lines.
Using csv.writerow instead of csv.writer to create the writer.