Linux日志文件系统开发问题:无法记录文本行删除操作
问题:无法记录日志文件系统中的行删除操作
我正在开发Linux下的日志文件系统项目,需要把文本文件的新增行和现有行删除操作记录到日志里,但现在没法记录行删除操作。我是编程新手,求帮忙!下面是使用pyinotify库的process_IN_MODIFY(self, event)方法代码片段:
with open(self.journal_files[file_path], "r") as f: self.lines = f.readlines() self.old_lines = self.lines.copy() with open(self.journal_files[file_path], "a") as f: # Check if any lines were added or removed for i, line in enumerate(lines): if i < len(lines) - 1: #if len(lines) < len(self.previous_lines): if line not in self.previous_lines and line.strip() != "": # Check if the line was added f.write(f"{current_time}, +, l{i+1}:{line}") # Check if the line was removed elif line not in self.previous_lines and len(lines) < len(self.previous_lines): f.write(f"{current_time}, -, l{i+1}:{line}") # if the line was in the previous lines else: # Check if the last line was removed #if len(lines) <= len(self.previous_lines): #if line not in self.previous_lines and line.strip() != "": f.write(f"{current_time}, +, l{i+1}:{line}") # Remember the current lines for the next time the file is modified self.previous_lines = lines
问题分析
你的代码无法捕获删除操作的核心原因:
- 遍历的是当前文件的行,但被删除的行只存在于历史行
self.previous_lines中,不在当前行里,遍历当前行根本找不到这些内容 - 删除判断逻辑完全颠倒:
line not in self.previous_lines是检测新增行,反过来才是找被删行 - 变量混乱:代码里用了未定义的
lines(应该是self.lines),且self.previous_lines缺少初始化,第一次运行会报错
修复后的代码
def process_IN_MODIFY(self, event): file_path = event.pathname # 生成格式化的当前时间,需提前导入datetime模块 current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 读取当前文件的所有行 with open(file_path, "r") as f: current_lines = f.readlines() # 打开对应日志文件准备写入 with open(self.journal_files[file_path], "a") as journal_f: # 先处理删除操作:找出历史行中不在当前行的内容 if self.previous_lines: for line_num, old_line in enumerate(self.previous_lines, start=1): if old_line not in current_lines and old_line.strip() != "": journal_f.write(f"{current_time}, -, l{line_num}:{old_line}") # 再处理新增操作:找出当前行中不在历史行的内容 for line_num, new_line in enumerate(current_lines, start=1): if new_line not in self.previous_lines and new_line.strip() != "": journal_f.write(f"{current_time}, +, l{line_num}:{new_line}") # 更新历史行,为下一次文件修改做准备 self.previous_lines = current_lines.copy()
注意事项
- 确保在类的
__init__方法中初始化self.previous_lines = [],避免首次运行报错 self.journal_files需正确映射目标文件路径到对应日志文件的路径- 如果处理大文件,用
in判断行存在性效率较低,可考虑用set(),但要注意重复行的问题;若需精准处理行的增减(包括重复行),可以使用Python内置的difflib库实现更细致的差异对比
内容的提问来源于stack exchange,提问作者persimmon
相关产品推荐
相关产品推荐

