Complete the code to open a CSV file for reading.
import csv with open('data.csv', [1]) as file: reader = csv.reader(file) for row in reader: print(row)
The mode 'r' opens the file for reading, which is needed to read CSV data.
Complete the code to write rows to a CSV file.
import csv with open('output.csv', 'w', newline=[1]) as file: writer = csv.writer(file) writer.writerow(['Name', 'Age']) writer.writerow(['Alice', 30])
Setting newline to an empty string prevents extra blank lines on some systems when writing CSV files.
Fix the error in the code to read CSV data as dictionaries.
import csv with open('data.csv', 'r') as file: reader = csv.DictReader(file) for row in [1]: print(row['Name'])
The variable 'reader' is the iterator over CSV rows as dictionaries.
Fill both blanks to create a dictionary from CSV rows where age is over 25.
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)
The dictionary keys are the 'Name' field and values are the integer 'Age' field for rows where age is greater than 25.
Fill all three blanks to write a CSV file with headers and two rows.
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])
Open the file in write mode ('w'), set newline to empty string to avoid blank lines, and use csv.writer to create the writer object.