首页 > 解决方案 > 捕获最后一个时间戳,无需使用 Python 读取完整文件

问题描述

我对python相当陌生,我试图使用python捕获系统日志文件的最后一行,但无法这样做。这是一个巨大的日志文件,所以我想避免将完整的文件加载到内存中。我只想读取文件的最后一行并捕获时间戳以进行进一步分析。

我有下面的代码,它将所有时间戳捕获到一个python dict中,一旦它完成我的计划是反转列表并捕获索引中的第一个对象[0],它需要很长时间才能运行到最后一个时间戳]:

lastFile 函数使用 glob 模块,并为我提供了最新的日志文件名,该文件名被输入到 main 函数的 recentEdit 中。

有没有更好的方法来做到这一点

脚本1:

#!/usr/bin/python
import glob
import os
import re

def main():
    syslogDir = (r'Location/*')
    listOfFiles = glob.glob(syslogDir)
    recentEdit  = lastFile(syslogDir)
    print(recentEdit)
    astack=[]
    with open(recentEdit, "r") as f:
        for line in f:
            result = [re.findall(r'\d{4}.\d{2}.\d{2}T\d{2}.\d{2}.\d{2}.\d+.\d{2}.\d{2}',line)]
            print(result)

def lastFile(i):
    listOfFiles = glob.glob(i)
    latestFile = max(listOfFiles, key=os.path.getctime)
    return(latestFile)



if __name__ == '__main__': main()

Script2:
###############################################################################
###############################################################################
#The readline() gives me the first line of the log file which is also not what I am looking for:



#!/usr/bin/python
import glob
import os
import re

def main():
    syslogDir = (r'Location/*')
    listOfFiles = glob.glob(syslogDir)
    recentEdit  = lastFile(syslogDir)
    print(recentEdit)
    with open(recentEdit, "r") as f:
        fLastLine = f.readline()
        print(fLastLine)
#    astack=[]
#    with open(recentEdit, "r") as f:
#        for line in f:
#            result = [re.findall(r'\d{4}.\d{2}.\d{2}T\d{2}.\d{2}.\d{2}.\d+.\d{2}.\d{2}',line)]
#            print(result)

def lastFile(i):
    listOfFiles = glob.glob(i)
    latestFile = max(listOfFiles, key=os.path.getctime)
    return(latestFile)



if __name__ == '__main__': main()

我真的很感谢你的帮助!!

真挚地。

标签: pythonregextimestampanalytics

解决方案


如果要直接转到文件末尾。按着这些次序:

1.每次您的程序运行时都会保留或存储最后一个'\n'索引。

2.如果您保留了最后一个'\n'的索引,那么您可以使用直接查找该索引

file.seek(yourpersistedindex)

3.之后,当你打电话时,file.readline()你会得到从你的持久索引开始的行。

4.每次运行脚本时存储此索引。

例如:您的文件log.txt的内容如下:

时间戳1 \n 时间戳2 \n 时间戳3 \n

import pickle
lastNewLineIndex = None
#here trying to read the lastNewLineIndex
try:
    rfile = open('pickledfile', 'rb')      
    lastNewLineIndex = pickle.load(rfile)
    rfile.close()
except:
    pass

logfile = open('log.txt','r')
newLastNewLineIndex = None
if lastNewLineIndex:
    #seek(index) will take filepointer to the index
    logfile.seek(lastNewLineIndex)
    #will read the line starting from the index we provided in seek function
    lastLine = logfile.readline()
    print(lastLine)
    #tell() gives you the current index
    newLastNewLineIndex = logfile.tell()
    logfile.close()
else:
    counter = 0
    text = logfile.read()
    for c in text:
        if c == '\n':
            newLastNewLineIndex = counter
        counter+=1


#here saving the new LastNewLineIndex
wfile = open('pickledfile', 'wb')
pickle.dump(newLastNewLineIndex,wfile)
wfile.close()

推荐阅读