How to write a file generator

Terry Reedy tjreedy at udel.edu
Tue Jul 12 14:02:15 EDT 2011


On 7/12/2011 10:46 AM, Billy Mays wrote:
> I want to make a generator that will return lines from the tail of
> /var/log/syslog if there are any, but my function is reopening the file
> each call:
>
> def getLines():
> with open('/var/log/syslog', 'rb') as f:
> while True:
> line = f.readline()
> if line:
> yield line
> else:
> raise StopIteration

Please use spaces rather than (disappearing) tabs in posted code.

> I know the problem lies with the StopIteration, but I'm not sure how to
> tell the caller that there are no more lines for now.

The same way you currently decide when to raise StopIteration

def tail(filename):
   with open(filename, 'rb') as f:
     while True:
       yield f.readline()

When the caller gets '', it should go and do something else for awhile.

-- 
Terry Jan Reedy




More information about the Python-list mailing list