Reading CSVs With Python's "csv" Module

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.txt') 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[3]}')

Using csv.DictReader():

import csv

with open('employee_birthday.txt') 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"]}')

Comments & Discussion

newoptionz on June 1, 2019

The code did not recognize the file in windows, I modified the path as follows

import csv
from pathlib import Path

data_folder1 = Path("C:/Users/Stephen/OneDrive/Documents/PythonCSV/")
data_folder1 = Path("C:\\Users\\Stephen\\OneDrive\\Documents\\PythonCSV\\")

file_to_open = data_folder1 / "employee_birthday.txt"

with open(file_to_open) as csv_file:

newoptionz on June 1, 2019

The magical powers of the . In the code above, the second data_folder1 had double \, not single ones as shown above.

josephjaewookim on June 15, 2019

It would be nice if you provided the actual CSV file…

Dan Bader RP Team on June 16, 2019

@josephjaewookim: You can find the CSV file by clicking on the “Supporting Material” button. But I’m also adding it to the description above, thanks for the heads up.

Become a Member to join the conversation.