grokking generators and iterators
Alex Martelli
aleax at aleax.it
Sat May 11 02:34:28 EDT 2002
Bob Horvath wrote:
...
> How would you suggest writing a generator that spits out 5 line chunks
> of a file at a time?
>
> How would you do it without generators?
class atatime:
def __init__(self, S, n=5):
self.it = iter(S)
self.r = range(n)
def next(self):
return [self.it.next() for i in self.r]
def __iter__(self):
return self
for li5 in atatime(open('somefile')):
print '5 more lines:', li5
Alex
More information about the Python-list
mailing list