Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Reading CSVs With Python's "csv" Module

Give Feedback

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

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

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.

Eric P on Aug. 16, 2019

Humm

Python 3.7.2

import csv
print(csv.__file__)

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]}')

gives me

/Users/epalmer/.virtualenvs/data_science/bin/python /Users/epalmer/projects_sorted/real_python/data_science/csv/read1.py
Traceback (most recent call last):
  File "/Users/epalmer/projects_sorted/real_python/data_science/csv/read1.py", line 4, in <module>
    csv_reader = csv.Reader(csv_file, delimiter=',')
AttributeError: module 'csv' has no attribute 'Reader'
/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py

Process finished with exit code 1

In pycharm and at the terminal.

Eric P on Aug. 16, 2019

Python 3 has a lowercase reader method in the csv module.

used in the repl to find out

dir(csv)

Also the code example under Using csv.Reader(): is not working. I’m just going to roll my own example because I have used the csv module before.

The Cool Ghoul on Sept. 17, 2019

I really like the tip about using the DictReader . Never knew that existed. I routinely read large CSV datasets. So this will be a big time saver and improve readability of my code.

Stibbsy on Oct. 17, 2019

Hey! Just wondering what the purpose of the line line_count=0 was in this snippet, as it doesn’t seem to get used anywhere?

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]}')

Joe Tatusko RP Team on Oct. 17, 2019

Hi Stibbsy! That line_count variable was in there to print out the number of lines processed in the csv, but would need to be incremented as each row is processed. I didn’t include that in the video, but left the variable in there. It’s not needed for the csv module to function correctly. Good find!

muralichintapalli on Feb. 1, 2020

there is no method csv.Reader its csv.reader

Ranit Pradhan on March 21, 2020

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 this code I got some following errors:-

AttributeError Traceback (most recent call last) <ipython-input-4-fae0f779c01c> in <module> 1 import csv 2 with open(‘employee_birthday.txt’) as csv_file: ----> 3 csv_reader = csv.Reader(csv_file, delimiter=’,’) 4 line_count = 0 5 for row in csv_reader:

AttributeError: module ‘csv’ has no attribute ‘Reader’

## I got the solution by changing csv.Reader to csv.reader and give the limit row[2] in place of row[3] because it was comming out of range.``

Ranit Pradhan on March 21, 2020

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”]}’)

//It needs to write as {row[“birthday month”]} in place of {row[“month”]}................as it’s already given in the text document employee_birthday.

wonderdog on March 28, 2020

Good tutorial and I am able to use this method for opening a single .csv file for reading - however I would like to open multiple .csv files at once.

How would a pythonista use the csv module - to open a variable number of .csv files for ‘reading’ (files that a user specifies at run time via the ‘input’ function) at the same time and dynamically assign a csv_reader, for each .csv file that is opened? Any help is much appreciated.

farlesh1000 on April 21, 2020

Fun (unnecessary) way to create the txt from scratch:

<p>from pathlib import Path

project_folder = Path(‘C:\Users\user_name\project_file_folder_name\‘) file_to_open = project_folder / ‘employee_birthday.txt’

fh = open(file_to_open, mode=’w’) # fh stands for file handler object

the only required parameter for open is mode, therefore you can just type ‘w’

fh.write(‘name,department,birthday month\n’ ‘John Smith,Accounting,November\n’ ‘Erica Meyers,IT,March’) fh.close()

shallah richardson on May 25, 2020

Hi are there files for this lesson if so where are they? The supporting material button only takes me to another tutorial. Thanks

shallah richardson on May 25, 2020

Hi are there files for this lesson if so where are they? The supporting material button only takes me to another tutorial. Thanks

Jon Fincher RP Team on May 26, 2020

shallahrichardson, check out the linked article. The files referenced can be found if you scroll through that article.

shallah richardson on May 26, 2020

@ Jon Fincher I’ve scrooled through all the comments and articles and I still don’t see the files.

Dan Bader RP Team on May 26, 2020

Here’s the direct link for the sample CSVs: realpython.com/courses/reading-and-writing-csv-files/downloads/reading-and-writing-csv-files-samples/

(They can also be found at the start of the course and under the Supporting Materials dropdown on each video lesson.)

theramstoss on June 18, 2020

Could you please explain why the python documentation requires newline = ‘’? I kind of understand it but not 100%. Thanks!

theramstoss on June 18, 2020

Also, the python docs does not seem to specify ‘r’. Is the default ‘r’?

UweSteiner on June 27, 2020

good overview of what’s possible with ZIP

Become a Member to join the conversation.