使用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
提交
取消