Get last n lines of a file with Python, similar to tail
Posted
by Armin Ronacher
on Stack Overflow
See other posts from Stack Overflow
or by Armin Ronacher
Published on 2008-09-25T21:11:11Z
Indexed on
2010/06/10
21:32 UTC
Read the original article
Hit count: 378
I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a tail()
method that can read n
lines from the bottom and supports an offset. What I came up with looks like this:
def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
Is this a reasonable approach? What is the recommended way to tail log files with offsets?
© Stack Overflow or respective owner