Why can’t I repeat the ‘for’ loop for csv.Reader?

The csv reader is an iterator over the file. Once you go through it once, you read to the end of the file, so there is no more to read. If you need to go through it again, you can seek to the beginning of the file:

fh.seek(0)

This will reset the file to the beginning so you can read it again. Depending on the code, it may also be necessary to skip the field name header:

next(fh)

This is necessary for your code, since the DictReader consumed that line the first time around to determine the field names, and it’s not going to do that again. It may not be necessary for other uses of csv.

If the file isn’t too big and you need to do several things with the data, you could also just read the whole thing into a list:

data = list(read)

Then you can do what you want with data.

Leave a Comment