How to write a file generator

Billy Mays noway at nohow.com
Tue Jul 12 10:46:38 EDT 2011


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


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.

--
Bill



More information about the Python-list mailing list