使用Python获取文件的最后n行,类似于tail我正在为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这是否一个合理的方法?建议使用什么方法来跟踪带有偏移量的日志文件?
3 回答
月关宝盒
TA贡献1772条经验 获得超5个赞
from collections import deque deque(f, maxlen=n)
import itertoolsdef maxque(items, size): items = iter(items) q = deque(itertools.islice(items, size)) for item in items: del q[0] q.append(item) return q
def tail(f, n): assert n >= 0 pos, lines = n+1, [] while len(lines) <= n: try: f.seek(-pos, 2) except IOError: f.seek(0) break finally: lines = list(f) pos *= 2 return lines[-n:]
添加回答
举报
0/150
提交
取消