1. 程式人生 > >python3讀取日誌檔案的最後一行內容

python3讀取日誌檔案的最後一行內容

(1)模擬建立一個日誌檔案.txt

關鍵字      日期和時間          來源                事件ID  任務類別
稽核成功	2018/9/11 12:17:15	Security-Auditing	4672	Special Logon
稽核成功	2018/9/11 12:17:15	Security-Auditing	4624	Logon
稽核成功	2018/9/11 12:17:14	Security-Auditing	4672	Special Logon
稽核成功	2018/9/11 12:17:14	Security-Auditing	4624	Logon
稽核成功	2018/9/11 12:17:07	Security-Auditing	4672	Special Logon
稽核成功	2018/9/11 12:17:07	Security-Auditing	4624	Logon
稽核成功	2018/9/11 12:09:27	Security-Auditing	4672	Special Logon
稽核成功	2018/9/11 12:09:27	Security-Auditing	4624	Logon

(2)用 seek()函式從後往前搜尋

f = open('日誌檔案','rb')
for i in f:
    offs = -70            #設定偏移量(估計最後一行長度)
    while True:
        f.seek(offs,2)
        data = f.readlines()
        if len(data) > 1:
            print(data[-1].decode('utf8'))
            break
        offs *=2            
f.close()
返回值:
稽核成功	2018/9/11 12:09:27	Security-Auditing	4624	Logon