Python日志检查脚本hit_unique_check方法联合运行失效问题求助
问题原因与修复方案
问题根源
文件对象是一次性迭代器:当equally_check方法遍历完self.current_file的所有行后,文件指针会停在文件末尾,后续hit_unique_check再遍历同一个文件对象时,无法读取到任何内容,导致unique_hit_list为空,最终错误返回"PASS: All hits are unique."。
另外你在run方法里写的print(self.current_file.readlines, "")只是打印了方法对象,没有实际读取内容,但即便调用readlines(),也会把指针移到文件末尾,同样会导致后续遍历无内容。
修复方案
推荐采用缓存文件内容的方式,避免文件指针操作的问题,同时提升效率:
修复后的完整代码
import os class ReadFiles: def __init__(self): self.current_lines = [] # 改为存储文件内容列表 self.shoot_from = "Shoot from" self.hit_player = "Hit player" def equally_check(self): shoot_from_list = [] hit_player_list = [] for line in self.current_lines: # 遍历缓存的行列表 if self.shoot_from in line: shoot_from_list.append(line) elif self.hit_player in line: hit_player_list.append(line) if len(shoot_from_list) == len(hit_player_list): print(" PASS: Shoots and hits are equal.\n") else: print(" FAIL: Shoots and hits are NOT equal.\n") def hit_unique_check(self): hit_lines = [] duplicates = set() # 用集合自动去重重复的行 for line in self.current_lines: if self.hit_player in line: hit_lines.append(line) for line in hit_lines: if hit_lines.count(line) > 1: duplicates.add(line) if not duplicates: print(" PASS: All hits are unique.\n") else: print(" FAIL: These hits are duplicated.\n") for dup_line in duplicates: print(dup_line) def run(self): for file in os.listdir(): if file.endswith(".log"): print(f"Log file - {file}") with open(file, 'rt') as f: # 用with语句自动管理文件关闭 self.current_lines = f.readlines() # 一次性读取所有行到列表 print(self.current_lines) self.equally_check() self.hit_unique_check() if __name__ == "__main__": runner = ReadFiles() runner.run()
关键修改点
- 缓存文件内容:将
self.current_file改为self.current_lines,一次性读取文件所有行到列表,后续所有方法都操作这个列表,彻底避免文件指针问题。 - 优化重复行检测:用
set存储重复行,避免原代码中重复添加同一行到duplicates列表的问题。 - 安全文件管理:使用
with语句自动关闭文件,无需手动调用close(),更安全可靠。 - 拼写修正:将错误的"This hits"改为"These hits"。
内容的提问来源于stack exchange,提问作者Viacheslav Stupin
相关产品推荐
相关产品推荐

