Python
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.
id,name,score
1,Jane Doe,10
2,John Doe,9
3,Alice,10
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.
csv
moduleTo work with CSV files in Python we take help of the csv
module.
Import the csv module by writing the following line.
import csv
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.
id,name,score
1,Jane Doe,10
2,John Doe,9
3,Alice,10
Python code to read CSV file.
# import module
import csv
try:
# 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:
rows.append(row)
# print rows
for r in rows:
for i in range(columnsCount):
print(fields[i] + " = " + r[i])
print("------")
except:
print("An error occurred while reading the file.")
finally:
fobj.close()
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
------
ADVERTISEMENT