Py学习  »  Python

python:从文件中读取最后的'n'行[重复]

nac001 • 4 年前 • 1615 次点击  

我正在为一个web应用程序编写一个日志文件查看器,为此我想对日志文件的行进行分页。文件中的项是基于最新项的行。

所以我需要一个 tail() 可读取的方法 n 从底部开始并支持偏移的线。我想到的是这样的:

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

这样做合理吗?使用偏移量跟踪日志文件的建议方法是什么?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43580
 
1615 次点击  
文章 [ 30 ]  |  最新文章 4 年前