Spring Deals - hours only!Up to 70% off on all courses and bundles.-Close
Introduction
Reading CSV files
4. Recognizing the header line
Summary

Instruction

Good job! As you know, the first line in a CSV file may contain a header specifying the names of the fields (columns).

If we know that there is a header line in our CSV file, we can make good use of it:

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:
      print('Columns found:', ", ".join(row))
    else:
      print('Department found:', ", ".join(row))
    line_count += 1

We introduced a new variable named line_count. This variable is increased each time we have processed a line. If the variable equals zero, which it always does on the first iteration through the loop, it means we're processing the first line – that is, the CSV header. You can see that the script's behavior is different for the first line, where we print "Columns found:".

Exercise

Again, load the people.csv file. This time:

  1. Don't print the first (header) line at all.
  2. Start each subsequent line with:
    Person number {x} :
  3. After the colon, insert a space and list all fields separated with commas followed by a single space. The end result should look like this:
    Person number 1 : John, M, USA, 27, 85.4
    Person number 2 : Kasia, F, Poland, 28, 60.5
    ...
    

    Stuck? Here's a hint!

    Use a counter variable just like we used the line_count variable in the example. If line_count is zero, do nothing. Otherwise, print a new line.

    You can use ", ".join(row) to conveniently print all fields separated with commas.