python: How to read CSV files

A common task for projects is to read in data from external sources. One common source is a CSV spreadsheet file, where data is separated by commas.

Python provides a library called "csv" and it seems to do the job pretty well.

import csv

try:
file = open("filename.csv", 'r')
except IOError:
print "There was an error opening the file"
return

first_run = True
reader = csv.reader(file)

for row in reader:
if first_run:
# This row is the header row
first_run = False
continue

print row

That's all there really is to it. The rest of the code really depends on how you want to treat the data. Be good to it.

qn2nw1

To write to the CSV file, see source.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog