1

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.

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

4 Comments

Oh!thanks!Does it means the reader has some point like thing exists?
Not sure what you mean @honesty1997. File objects remember file offset they last worked with, so if you need to interact with a file multiple times using the same file object (f in this example), make sure to reset that location to the beginning.
Thanks!Does it means that in this case after I looped through the file, the next time I wanted to loop it again and got nothing because that the file object remember that last time I loop through the file and stop at the end of the object?
You got it @honesty1997.
0

You can try like this way to only get the headers.

import csv
f = open('file.csv')
csvDictInstance = csv.DictReader(f)
print csvDictInstance.fieldnames

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.