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

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

first_run = True
reader = csv.reader(file)

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

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.


To write to the CSV file, see source.

[ Source ]

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