【问题标题】:Check if log file has been updated / only parse new data - Python检查日志文件是否已更新/仅解析新数据 - Python
【发布时间】:2026-02-07 01:05:01
【问题描述】:

我有一个日志文件,我想每隔n 秒(或在它被修改时)检查是否有新数据附加到它上面。 我检查行数,如果之前的计数

def parse_file(path, index_to_start_parsing):
    //Parse the file

file_path = r"my_log_path"
previous_lines_count = 0
check_seconds = 5

while True:
    time.sleep(check_seconds)
    with open(file_path) as f:
        current_lines_count = sum(1 for _ in f)

    if current_lines_count > lines_count:
        data = parse_file(file_path, previous_lines_count)
        previous_lines_count = current_lines_count

它有效,但我正在寻找一种更优化的方法。 如何检查文件是否已更改(我阅读了有关 watchdog 的信息)如何才能以更有效的方式仅解析附加到文件的新数据。

编辑:

我使用os.stat('somefile.txt').st_size 来检查文件是否更改。

【问题讨论】:

    标签: python parsing logging


    【解决方案1】:

    当您在初始通道中完成读取时,使用f.tell() 来发现文件指针的当前偏移量。在以后的遍历中,使用f.seek() 将文件指针前进到文件中的前一个点,然后照常继续读取。

    offset = 0
    while True:
        f = open(file)
        f.seek(offset)
    
        while line = f.readline():
            # process...  
            pass
    
        offset = f.tell()
        f.close()
        # wait until next iteration
    

    这是一个古老的 C 技巧。

    更多信息here

    检查文件是否被修改通常就像looking at the file size 一样简单,看看它是否与您上次查看的相同。

    【讨论】: