[Tutor] python 2.4 reading files - unexpected behaviour

bob gailer bgailer at alum.rpi.edu
Fri Nov 23 20:35:27 CET 2007


John Gerdeman wrote:
> Hello, 
>
> I got a csv file, in which I have to count the occurrences of certain
> numbers in columns. I can do this for one arbitrary column, but not for
> all.
>
> The problem I encountered is as follows. Iterating through the rows of a
> file works, but as soon as I try to iterate through the same file again,
> it seems it returns nothing.
>
> Code-example
> ------------
> import csv
> file = csv.reader(open("some.csv", "rb"))
>   
It is not a good idea to use "file" as a variable name since that hides 
the built-in function. But that is not the reason you get what you do.
> for i in file:
> 	print i
>   
The file is now at end-of-file. Any attempts to read it now just keep it 
at end-of-file.  Either re-open it or file.seek(0) to rewind it to the 
beginning.
> for i in file:
> 	print i
>
>   



More information about the Tutor mailing list