Reputation: 415
I am encountering some weird things here.I am using python's csv module to process csv file. The example code is below
import csv
f = open('file.csv','r')
for i in csv.reader(f):
print i
This prints out all rows as lists and works just fine.And then when I want to do another thing like
for i in csv.DictReader(f):
print i['header']
Think this should print all the data with the header called 'header'.It failed.Then I tried a lot.I found I need to run the open file function again each time I run some csv method.It seems redundant to me.Think i might miss some steps.
Upvotes: 1
Views: 189
Reputation: 3461
You can try like this way to only get the headers.
import csv
f = open('file.csv')
csvDictInstance = csv.DictReader(f)
print csvDictInstance.fieldnames
Upvotes: 0
Reputation: 5532
When you're done reading the file the first time, you need to seek back to its beginning to read it again. Something like f.seek(0,0)
.
Upvotes: 3