Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Reading CSV files
10. Summary


Excellent! It's time to wrap things up.

  1. 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:
  2. When using csv.reader, use square brackets to access specific fields inside a for loop: row[0], row[1], etc.
  3. 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 the fieldnames argument:
    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'].
  4. 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?


Click Next exercise to continue.