[Tutor] Problem iterating over csv.DictReader
zstumgoren at gmail.com
Mon Apr 26 17:57:09 CEST 2010
> I have noticed this odd behaviour in the CSV DictReader Class, and at a
> loss to understand/ get around it.
> The aim is to read in a CSV file, and then iterate over the lines. The
> problem (seems) to be that once you have iterated over it once, you can't do
> it again.
> This is expected behavior. See below from the Python docs:
If you'd like to make multiple passes over the lines from your CSV, store
them in a variable when you first read them in and then loop over that
One approach (though it may not be the best if you're dealing with huge
quantities of data):
reader = csv.DictReader(open(fname, 'r'), delimiter = ',', quotechar = '"')
data = [row for row in reader]
# now you can make multiple passes over the dictionaries stored in "data"
> I don't know if this is me (and it may well be) but it seems to be a
> recurrent issue, and means that a csv.DictReader doesn't behave in the same
> way as a normal dict object.
Correct. It's not supposed to behave like a normal dict. It behaves like a
reader object. See the python docs:
"Create an object which operates like a regular reader but maps the
information read into a dict whose keys are given by the optional *
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor