且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用Python获取文件的最后n行,类似于尾部

更新时间:2023-01-13 19:10:22

我最终使用的代码。我认为这是迄今为止***的:

$ $ $ $ $ $ $ $ $ def尾(f,n,offset =无):
从偏移行的偏移量中读取f行,返回的
值是一个以``(lines,has_more)``形式存在的元组,其中`has_more`是
指示符是`如果文件中有更多的行,则为真。

avg_line_length = 74
to_read = n +(offset or 0)

while 1:
试试:
f.seek( - (avg_line_length * to_read),2)
除了IOError:
#woops。显然文件是小于我们想要的
#退后一步,去开始,而不是
f.seek(0)
pos = f.tell()
lines = f .read()。splitlines()
if len(lines)> = to_read或pos == 0:
return lines [-to_read:offset and -offset or None],\
len(行)> to_read或pos> 0
avg_line_length * = 1.3


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?

The code I ended up using. I think this is the best so far:

def tail(f, n, offset=None):
    """Reads a n lines from f with an offset of offset lines.  The return
    value is a tuple in the form ``(lines, has_more)`` where `has_more` is
    an indicator that is `True` if there are more lines in the file.
    """
    avg_line_length = 74
    to_read = n + (offset or 0)

    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], \
                   len(lines) > to_read or pos > 0
        avg_line_length *= 1.3