Open Source Projects
In this tutorial we will learn to read CSV file in Python.
A CSV or Comma Separated Values is a plain text file containing tabular data in printable ASCII or Unicode characters.
Points to note!
CSV files are saved with .csv extension.
You can create CSV files using text editors like Notepad, Sublime Text etc.
You can also use application like MS-Excel to create CSV files.
In the following example we have the content of a sample CSV file containing 4 rows and 3 columns.
The first row of the file is generally the name of the columns.
The above file has 3 columns - id, name and score. The remaining three rows contain the data.
To work with CSV files in Python we take help of the csv module.
Import the csv module by writing the following line.
To read CSV file data we take help of the reader() method of the csv module.
In the following Python program we are reading the content of the data.csv file and printing its content in the console.
Content of the data.csv file.
Python code to read CSV file.
# import module
# open file
fobj = open('data.csv', 'r')
# reader object
csvReader = csv.reader(fobj)
# get the field name
fields = csvReader.next()
# total columns
columnsCount = len(fields)
# iterate the rows
rows = 
for row in csvReader:
# print rows
for r in rows:
for i in range(columnsCount):
print(fields[i] + " = " + r[i])
print("An error occurred while reading the file.")
The above Python code will give us the following output.
id = 1
name = Jane Doe
score = 10
id = 2
name = John Doe
score = 9
id = 3
name = Alice
score = 10
Have fun learning :-)
Copyright © 2014 - 2019 DYclassroom. All rights reserved.
rendered in 0.0147 sec