Spring Deals - hours only!Up to 70% off on all courses and bundles.-Close
Reading CSV files
3. Parsing CSV files


Good job! Now, we'll actually parse our CSV file, but we'll still only print its contents line by line. Take a look:

import csv
with open('departments.csv') as csv_file:
  csv_reader = csv.reader(csv_file)
  for row in csv_reader:

On line 1, we import the csv module that's available in the Python standard library. On line 2, we use the open() function to open the departments.csv file. As we said before, CSV files are essentially text files, so they can be opened in Python just like any other text file. The resulting records are stored in the csv_reader variable. To access them one by one as a list of strings, we use a for loop on line 4, and then we print individual records on line 5.


Again, load the file named people.csv, and print its contents line by line just like we did in the example. Take a look at the output.

As you can see, the CSV reader correctly identified all the fields and records in our file. The first line is the header, which denotes the names of the fields (columns). Note that by default, each record is read as a list of strings (all fields are read as strings).

Stuck? Here's a hint!

Use the code from the explanation. Change the file name.