Instruction
Excellent! It's time to wrap things up.
- You can use the template below to load and parse a CSV file:
import csv with open('file_name.csv') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: ... - When using
csv.reader, use square brackets to access specific fields inside a for loop:row[0],row[1], etc. - When your CSV file contains a header row, you can obtain dictionaries instead of lists for the rows with
csv.DictReader():with open('file_name.csv') as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: ...You can also set your own field names, by using thefieldnamesargument:csv_reader = csv.DictReader(csv_file, fieldnames=['Department Name', 'Number of Employees', 'Department Budget'])
Inside the loop, you can access the fields using the following syntax:row['field_name']. - If your CSV file does not use commas as delimiters or quotation marks as quotation characters, you can change the default parsing behavior:
csv.reader(csv_file, delimiter=';', quotechar="'")
csv.DictReader(csv_file, delimiter=';', quotechar="'")
How about a short task to check your skills now?
Exercise
Click to continue.



