CSV files in python

I spent some time today working out how to deal with commas in a quoted csv files ( ie. 123,"sd,sd","sdggg" and that comma in the middle) when it suddenly dawned on me that I would not be the first to have tried this. Low and behold the python csv module:

import csv
csvdata = csv.reader(open("yourfile.csv", "rb"))
for line in csvdata:
    print line[2]

As per usual python comes with batteries included so it's always worth checking the library reference first before wasting some time thinking.

blog comments powered by Disqus