I'm writing a program that will parse an Apache log file periodically to log it's visitors, bandwidth usage, etc..
The problem is, I don't want to open the log and parse data I've already parsed. For example:
line1
line2
line3
If I parse that file, I'll save all the lines then save that offset. That way, when I parse it again, I get:
line1
line2
line3 - The log will open from this point
line4
line5
Second time round, I'll get line4 and line5. Hopefully this makes sense...
What I need to know is, how do I accomplish this? Python has the seek() function to specify the offset... So do I just get the filesize of the log (in bytes) after parsing it then use that as the offset (in seek()) the second time I log it?
I can't seem to think of a way to code this >.<
Easy but not recommended :):
Here is code proving using the length sugestion of yours and the tell methond:
If your logfiles fit easily in memory (this is, you have a reasonable rotation policy) you can easily do something like:
If you cannot do this, you can use something like (see accepted answer's use of seek and tell, in case you need to do it with them) Get last n lines of a file with Python, similar to tail
If you're parsing your log line per line, you could juste save line number from the last parsing. You would juste have then to start read it from the good line the next time.
Seeking is more usefull when you have to be in a very specific place in the file.
Here is an efficient and safe snippet to do that saving the offset read in a parallell file. Basically logtail in python.
Note that you can seek() in python from the end of the file:
puts the read position 3 lines from the EOF.
However, why not use diff, either from the shell or with difflib?