Saturday, September 6, 2014

Python: reading a csv file

Here's a csv file:
col 1,col 2,col 3
foo,bar,baz
one,two,three
42,,0 

This file can be read in python with this script:
import csv

csv_file   = open('data.csv', 'r')
csv_reader = csv.reader(csv_file)

header = csv_reader.next()

for record in csv_reader:
    
    print 'Record:'
    
    i = 0
    for rec_value in record:
        print '  ' + header[i] + ': ' + rec_value
        i += 1 

Github links: data.csv and script.py.

No comments:

Post a Comment