Lesson 10
I am Your Father
Chapter 7: More file handling
Reading CSV files
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 |
|
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 thecsv_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).