You are on page 1of 2

Python Programming home

Department of Computing, Imperial College London

Python for C++ Programmers


Chapter 1: Introduction
Chapter 2: Basic data types
Chapter 3: Variables and operators
Chapter 4: Sequence types
Chapter 5: Sets and dictionaries
Chapter 6: Control flow
Chapter 7: Functions
Chapter 8: Object-oriented programming
Chapter 9: Modules
Chapter 10: Files
[10.1] Handling text files
[10.2] JSON files
[10.3] Loading JSON files
[10.4] Writing to JSON files
[10.5] pickle
[10.6] Pickling time!
[10.7] CSV files
[10.8] Reading CSV files
[10.9] Reading CSV files into a dict
[10.10] Writing to CSV files
[10.11] That's a wrap!

Chapter 10: Files


>> 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 import csv
2
3 with open("students.csv") as csv_file:
4 reader = csv.reader(csv_file, delimiter=",")
5 header_row = next(reader)
6 print(f"Column names are {", ".join(header_row)}")
7
8 for row in reader:
9 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).

Previous Next 

Page designed by Josiah Wang Department of Computing | Imperial College London

You might also like