Spring Deals - hours only!Up to 70% off on all courses and bundles.-Close
Reading CSV files
5. Using specific fields


Great job! In the previous two exercises, we only used entire rows (i.e., we didn't access any specific fields within those rows).

Now, let's analyze how we can pick the information we want from rows. In the example below, we only print information on departments whose budgets exceed $350,000.00:

import csv
with open('departments.csv') as csv_file:
  csv_reader = csv.reader(csv_file)
  line_count = 0
  for row in csv_reader:
    if line_count > 0 and float(row[2]) > 350000.0:
      print('The', row[0], 'department has a budget of',row[2], 'USD.')
    line_count += 1

As we've seen before, each row in our CSV file is essentially a list of strings. This means we can access its elements using square brackets: row[0] is the first field, row[1] is the second field, etc. We know the structure of our CSV file, and we know that row[2] (the third field) is the department's budget. That's why we wrote the condition float(row[2]) > 350000.0. Remember that the CSV parser treats all fields as strings, so we have to convert row[2] to float.


Print the following line for every person (from people.csv) older than 27:

{name} comes from {country} and is {age} years old.

You can find name in the first column, country in the third, and age in the fourth. Don't print the header line.

Note: from now on, we will be importing the csv module for you. 🙂

Stuck? Here's a hint!

The person's age is given in the fourth column (row[3]). Convert this column to an integer with int(row[3]), and check if it's greater than 27.