How to stop iteration with __iter__() ?

Jeff jeffober at gmail.com
Tue Aug 19 13:55:47 CEST 2008


On Aug 19, 7:39 am, ssecorp <circularf... at gmail.com> wrote:
> I want a parse a file of the format:
> movieId
> customerid, grade, date
> customerid, grade, date
> customerid, grade, date
> etc.
>
> so I could do with open file as reviews and then for line in reviews.
>
> but first I want to take out the movie id so I use an iterator.
>
> then i want to iterate through all the rows, but how can I do:
> while movie_iter != None:
>
> because that doesn't work, itraises an exception, StopItreation, which
> according to the documentation it should. But catching an exception
> can't be the standard way to stop iterating right?

No.  If you are defining the iterator, then the iterator raises
StopIteration when it is complete.  It is not an exception you
normally catch; you use a for loop to iterate, and the machinery of
the for loop uses the StopIteration exception to tell it when to
break.  A file-like object is itself a line iterator, so:

def review_iter(file_obj):
  for line in file_obj:
    if matches_some_pattern(line):
      yield line

Then, to use it:

file_obj = open('/path/to/some/file.txt')
try:
  for review in review_iter(file_obj):
    do_something(review)
finally:
  file_obj.close()



More information about the Python-list mailing list