私信  •  关注

David Rogers

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

如果文件没有以结尾,或者无法确保读取完整的第一行,这些解决方案中有几个会有问题。

def tail(file, n=1, bs=1024):
    f = open(file)
    f.seek(-1,2)
    l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
    B = f.tell()
    while n >= l and B > 0:
            block = min(bs, B)
            B -= block
            f.seek(B, 0)
            l += f.read(block).count('\n')
    f.seek(B, 0)
    l = min(l,n) # discard first (incomplete) line if l > n
    lines = f.readlines()[-l:]
    f.close()
    return lines