csv iterator question

alex23 wuwei23 at gmail.com
Fri May 23 21:40:15 EDT 2008


On May 24, 6:36 am, davidj411 <davidj... at gmail.com> wrote:
> but when i try to iterate through it again, it appears to print
> nothing (no error either). the file is exhausted?

No, the iterator is finished. Iterators are generally use-once:

"The intention of the protocol is that once an iterator's next()
method raises StopIteration, it will continue to do so on subsequent
calls. Implementations that do not obey this property are deemed
broken." [http://docs.python.org/lib/typeiter.html]

As well as reading the iterator into a list, you can also create a
copy of the iterator:

>>> import itertools
>>> reader1, reader2 = itertools.tee(csv.reader(open('export.csv')))

Two copies is the default, but you can optionally specify as many as
you like:

>>> m, n, o = itertools.tee(iterator, 3)

- alex23







More information about the Python-list mailing list