python: How to read CSV files

0 Comments

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.

01.import csv
02. 
03.try:
04.  file = open("filename.csv", 'r')
05.except IOError:
06.  print "There was an error opening the file"
07.  return
08. 
09.first_run = True
10.reader = csv.reader(file)
11. 
12.for row in reader:
13.  if first_run:
14.    # This row is the header row
15.    first_run = False
16.    continue
17. 
18.  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