私信  •  关注

Hauke Rehfeld

Hauke Rehfeld 最近创建的主题
Hauke Rehfeld 最近回复了
6 年前
回复了 Hauke Rehfeld 创建的主题 » python:从文件中读取最后的'n'行[重复]

一个更干净的python3兼容版本,不插入,但追加和反转:

def tail(f, window=1):
    """
    Returns the last `window` lines of file `f` as a list of bytes.
    """
    if window == 0:
        return b''
    BUFSIZE = 1024
    f.seek(0, 2)
    end = f.tell()
    nlines = window + 1
    data = []
    while nlines > 0 and end > 0:
        i = max(0, end - BUFSIZE)
        nread = min(end, BUFSIZE)

        f.seek(i)
        chunk = f.read(nread)
        data.append(chunk)
        nlines -= chunk.count(b'\n')
        end -= nread
    return b'\n'.join(b''.join(reversed(data)).splitlines()[-window:])

像这样使用:

with open(path, 'rb') as f:
    last_lines = tail(f, 3).decode('utf-8')