0
0
Pythonprogramming~10 mins

Working with CSV files 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 named 'data.csv' for reading.

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

Complete the code to import the module needed to work with CSV files.

Python
[1] csv
Drag options to blanks, or click blank then click option'
Afrom
Busing
Crequire
Dimport
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'from' without specifying what to import.
Using 'require' which is not Python syntax.
3fill in blank
hard

Fix the error in the code to read rows from a CSV file using csv.reader.

Python
with open('data.csv', 'r') as file:
    reader = csv.[1](file)
    for row in reader:
        print(row)
Drag options to blanks, or click blank then click option'
Areader
Bread_csv
Creadlines
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read' which is a file method, not csv module.
Using 'read_csv' which is from pandas, not csv module.
4fill in blank
hard

Fill both blanks to write rows to a CSV file using csv.writer.

Python
with open('output.csv', [1]) as file:
    writer = csv.[2](file)
    writer.writerow(['Name', 'Age'])
Drag options to blanks, or click blank then click option'
A'w'
B'r'
Cwriter
Dreader
Attempts:
3 left
💡 Hint
Common Mistakes
Opening file in 'r' mode when writing.
Using csv.reader() instead of csv.writer().
5fill in blank
hard

Fill all three blanks to create a dictionary from CSV rows using csv.DictReader and print the 'Name' field.

Python
with open('data.csv', [1]) as file:
    reader = csv.[2](file)
    for row in reader:
        print(row[[3]])
Drag options to blanks, or click blank then click option'
A'r'
BDictReader
C'Name'
D'w'
Attempts:
3 left
💡 Hint
Common Mistakes
Opening file with 'w' when reading.
Using csv.reader instead of DictReader.
Trying to access row with wrong key.