In this video, you’ll learn how to read standard CSV files using Python’s built in csv
module. There are two ways to read data from a CSV file using csv
. The first method uses csv.Reader()
and the second uses csv.DictReader()
.
csv.Reader()
allows you to access CSV data using indexes and is ideal for simple CSV files. csv.DictReader()
on the other hand is friendlier and easy to use, especially when working with large CSV files.
We’ll be using the following sample CSV file called employee_birthday.csv
:
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
The following code samples show how to read CSV files using the two methods:
Using csv.Reader()
:
import csv
with open('employee_birthday.csv') as csv_file:
csv_reader = csv.Reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}')
Using csv.DictReader()
:
import csv
with open('employee_birthday.csv') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["month"]}')
newoptionz on June 1, 2019
The code did not recognize the file in windows, I modified the path as follows