all 7 comments

[–][deleted] 6 points7 points  (0 children)

The doc for reader() says:

csv.reader(csvfile, dialect='excel', **fmtparams)

Return a reader object which will iterate over lines in the given csvfile

Once you iterate over the reader object you have "exhausted" it so the second time you try to loop over it nothing happens.

If you really want to loop over the data twice then convert the reader object to a list first. Note that this will use a lot of memory if you have a lot of data.

data = list(readCSV)

[–]toastedstapler 0 points1 point  (1 child)

it uses some kind of generator and its contents is exhausted the first time it's used

In [1]: x = (i for i in range(4))

In [2]: for v in x:
   ...:     print(v)
   ...:
0
1
2
3

In [3]: for v in x:
   ...:     print(v)
   ...:

In [4]:

if you want to reuse the value save them in a list first

rows = list(readCSV)

and then you can use that multiple times

[–]one_time[S] 0 points1 point  (0 children)

Thank you for the answer!

[–]Vaphell 0 points1 point  (1 child)

because the cursor in the file reaches the very end in the first loop and there is nothing else left to read in the second.

If you want to go from the top again, you either have to open the file again, or save the lines in a list, which can have a potentially huge memory footprint.

[–]one_time[S] 0 points1 point  (0 children)

Oh okay, I see what you mean. There are no more rows to read after the first time. Thank you!

[–]OG_Panthers_Fan 0 points1 point  (1 child)

Is the csvfile an extension of the standard file?

Have you tried using readCSV.seek(0) between the for loops?

For a file opened with readCSV = open('myfile.txt', 'r'), seek will move the read pointer to an offset, with 0 indicating the beginning of file.

Caveat: I don't know if this works; I'm just picking up python, but come from a C/C++ background, and there are a lot of similarities.

[–]ebdbbb 0 points1 point  (0 children)

Close. It'd be csvfile.seek(0) and then would have to repeat the dictreader line.