This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 7: More file handling

Reading CSV files

face Josiah Wang

Let’s say I have a CSV file called students.csv with the content below.

name,faculty,department
Alice Smith,Science,Chemistry
Ben Williams,Eng,EEE
Bob Jones,Science,Physics
Andrew Taylor,Eng,Computing

Let’s use the csv module to read this file.

1
2
3
4
5
6
7
8
9
import csv

with open("students.csv") as csv_file: 
    reader = csv.reader(csv_file, delimiter=",") 
    header_row = next(reader) 
    print(f"Column names are {", ".join(header_row)}")

    for row in reader: 
        print(f"Student {row[0]} is from the Faculty of {row[1]}, {row[2]} dept.")

The expected output is:

Column names are name, faculty, department
Student Alice Smith is from the Faculty of Science, Chemistry dept. 
Student Ben Williams is from the Faculty of Eng, EEE dept. 
Student Bob Jones is from the Faculty of Science, Physics dept. 
Student Andrew Taylor is from the Faculty of Eng, Computing dept.

Examining the code:

  • Line 4 constructs a csv.reader object from the given CSV file object. You can also optionally specify the separator to be a comma (this is the default value).
  • Line 5 uses the next() to get the next item from the csv_reader (an iterable). Here we are reading the first line, which contains the column headers.
  • Line 8 reads each remaining row as a list of str items. The module automatically splits the row into columns using the specified separator in Line 4 (or comma by default).