How to read CSV files in Python
Published on: 15th September 2018
This tutorial demonstrates Python way of reading CSV files into either dictionary or list data structures.
Abstract
In this tutorial we will read a CSV file to get the data in the form of List and Dictionary data structures.
Implementation
We will now see how to read following CSV file into List and List of Dictionary -
Id,Title,Value
1,Python,24
2,Java,43
3,PHP,23
4,.net,29
I have got this file saved on path D:\Python_reading.csv in my machine.
Reading CSV file into List
import csv
#Reading CSV file as a List
with open('D:\Python_reading.csv', 'rb') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader) #to remove csv header
for row in csvreader:
print row
Output:
['1', 'Python', '24']
['2', 'Java', '43']
['3', 'PHP', '23']
['4', '.net', '29']
Reading CSV file into Dictionary
import csv
#Reading CSV file as a Dictionary
with open('D:\Python_reading.csv', 'rb') as csvfile:
dictreader = csv.DictReader(csvfile)
for r in dictreader:
print r
Output:
{'Id': '1', 'Value': '24', 'Title': 'Python'}
{'Id': '2', 'Value': '43', 'Title': 'Java'}
{'Id': '3', 'Value': '23', 'Title': 'PHP'}
{'Id': '4', 'Value': '29', 'Title': '.net'}
Reading CSV file into List of Dictionary
import csv
#Reading CSV file as a list of dictionary
with open('D:\Python_reading.csv', 'rb') as csvfile:
listdictreader = csv.DictReader(csvfile)
data = [val for val in listdictreader]
print data
Output:
[{'Id': '1', 'Value': '24', 'Title': 'Python'}, {'Id': '2', 'Value': '43', 'Title': 'Java'}, {'Id': '3', 'Value': '23', 'Title': 'PHP'}, {'Id': '4', 'Value': '29', 'Title': '.net'}]
Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.
Published on: 15th September 2018
Comment Form is loading comments...