【发布时间】: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 来检查文件是否更改。
【问题讨论】: