[Tutor] parsing a continuous log file

Michael H. Goldwasser goldwamh at slu.edu
Fri Nov 30 02:08:46 CET 2007

The for loop below will exit once it hits EOF (and will not continue
if more data is later appended.  But as Alan says, a while loop will
suffice.  I've tested the following variant.

import time
f = file('foo.txt')

while True:
    line = f.readline()
    if line:
        print "do what you want with", line
    else:                 # currently at end of file
        time.sleep(1)     # don't want to poll too quickly

Good luck,

On Friday November 30, 2007, Alan Gauld wrote: 

>    "ray sa" <bizag007 at yahoo.com> wrote
>    > used in UNIX called the tail command.
>    >
>    > May be someone can help me to achieve the same result with modifying 
>    > the above code?
>    Sorry i didnm't look too closely but i think you should only need to 
>    keep the file open andd then  loop around with a delay.
>    Sometjing like:
>    try:
>      f = open('foo.txt')
>      for line in f:
>         print line
>         time.sleep(1)
>    finally:
>       f.close()
>    That will keep reading the lines until it hits the end of the file.
>    Of course if the file is eventually empty then it exits so you
>    may want a while True loop instead and only print if the line is non 
>    empty

More information about the Tutor mailing list