Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' will overwrite the file.
Using 'a' opens for appending, not reading.
✗ Incorrect
To read a file, you open it with mode 'r'.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'from' without specifying what to import.
Using 'require' which is not Python syntax.
✗ Incorrect
The correct way to import a module in Python is using 'import'.
3fill in blank
hardFix 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'
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.
✗ Incorrect
The csv module uses csv.reader() to read CSV files row by row.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Opening file in 'r' mode when writing.
Using csv.reader() instead of csv.writer().
✗ Incorrect
To write to a file, open it with 'w' mode and use csv.writer() to write rows.
5fill in blank
hardFill 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'
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.
✗ Incorrect
Open the file for reading, use csv.DictReader to read rows as dictionaries, then print the 'Name' field.