Ethan Whitt
Ethan Whitt

Reputation: 167

How to repeatedly read a file from the last location

I am trying to read a syslog repeatedly and only start from the point I left off last read. I am trying to save the location of tell() is a sperate file and reload to seek before every read.



    lf = open("location.file", 'r')
    s = lf.readline()
    last_pos = int(s.strip())
    lf.close()

    sl = open("/var/log/messages", 'r')
    sl.seek(last_pos)
    for line in sl.readlines():
         # This should be the starting point from the last read
    last_loc = sl.tell()

    lf = open("location.file", "w+")
    lf.write(last_loc)
    lf.close()


Upvotes: 3

Views: 791

Answers (2)

agf
agf

Reputation: 176730

  1. Write str(last_loc) instead of last_loc.

    The rest are probably optional.

  2. Use w instead of w+ for writing the location.
  3. Close /var/log/messages when you're done with it.
  4. Depending on your version of Python (definitely on 2.6 or newer, maybe on 2.5 depending), you may want to use with to automatially close files.
  5. You probably don't need strip if you're just writing the value.
  6. You can just use read instead of readline on lf.
  7. You can iterate over the file itself, rather than using readlines, for sl.

    try:
        with open("location.file") as lf:
            s = lf.read()
            last_pos = int(s)
    except:
        last_post = 0
    
    with open("/var/log/messages") as sl:
        sl.seek(last_pos)
        for line in sl:
            # This should be the starting point from the last read
        last_loc = sl.tell()
    
    with open("location.file", "w") as lf:
        lf.write(str(last_loc))
    

Upvotes: 3

Foo Bah
Foo Bah

Reputation: 26251

Your readline is weird. What you nee to do is either:

1) save the value as a string and parse it:

lf.write(str(last_loc))

2) save and reread the location as an int:

lf.write(struct.pack("Q",lf.tell()))
last_pos = struct.unpack("Q",lf.read())

Upvotes: 0

Related Questions