亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Python獲取文件的最后n行,類似于tail

使用Python獲取文件的最后n行,類似于tail

臨摹微笑 2019-06-20 16:57:22
使用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個贊

如果讀取整個文件是可以接受的,那么使用deque。

from collections import deque
deque(f, maxlen=n)

在2.6之前,deques沒有maxlen選項,但是很容易實現。

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

如果需要從末尾讀取文件,則使用gallop(即指數搜索)。

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:]


查看完整回答
反對 回復 2019-06-20
  • 3 回答
  • 0 關注
  • 1966 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號