Reading and Writing CSV Files with Python DictReader and DictWriter

Python ScriptingPython can be an extremely powerful tool for reading and writing csv files. Here I’ll demonstrate an example of each using the csv DictWriter function.

Sample File: (test.csv)
firstname,lastname,age,favoritecolor
john,smith,24,red
jane,doe,26,blue
sophe,miller,33,yellow
jason,doe,21,red

From here, I will import the csv file into a dictionary array using the csv DictReader function in the python console.

import csv
test_file = 'test.csv'
csv_file = csv.DictReader(open(test_file, 'rb'), delimiter=',', quotechar='"')

You can now parse through the data as a normal array.

for line in csv_file:
    print line['age']

24
26
33
21

Writing an array to a csv file with DictWriter

Here is an example of using DictWriter to write a csv file. The main difference is that the fieldnames have to be entered as a separate array. The fieldnames have to match all of the keys in the dictionary array but can be ordered differently.

test_array = []
test_array.append({'fruit': 'apple', 'quantity': 5, 'color': 'red'});
test_array.append({'fruit': 'pear', 'quantity': 8, 'color': 'green'});
test_array.append({'fruit': 'banana', 'quantity': 3, 'color': 'yellow'});
test_array.append({'fruit': 'orange', 'quantity': 11, 'color': 'orange'});
fieldnames = ['fruit', 'quantity', 'color']
test_file = open('test2.csv','wb')
csvwriter = csv.DictWriter(test_file, delimiter=',', fieldnames=fieldnames)
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
for row in test_array:
     csvwriter.writerow(row)
test_file.close()

The writeheader() function was added to DictWriter in 2.7 and gives a cleaner way to write the first row of the csv file. You could replace line 9 with it, but I would advise against it to maintain backward compatibility.

Results of test2.csv after using the csv DictWriter:
fruit,quantity,color
apple,5,red
pear,8,green
banana,3,yellow
orange,11,orange

2 thoughts on “Reading and Writing CSV Files with Python DictReader and DictWriter”

Leave a Comment

Your email address will not be published. Required fields are marked *