【发布时间】:2022-11-15 10:46:52
【问题描述】:
我需要在日志文件中进行两次检查并显示结果。单独的方法可以正常工作,但是当我运行所有代码方法时hit_unique_check总是返回“PASS:所有命中都是独一无二的。”。对于三个中的两个。日志文件这个结果是不正确的。
import os
class ReadFiles:
def __init__(self):
self.current_file = ""
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_file:
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):
unique_hit_list = []
duplicates = []
for line in self.current_file:
if self.hit_player in line:
unique_hit_list.append(line)
else:
continue
for i in unique_hit_list:
if unique_hit_list.count(i) > 1:
duplicates.append(i)
print(i)
else:
continue
if len(duplicates) < 1:
print(" PASS: All hits are unique.\n")
else:
print(" FAIL: This hits are duplicated.\n")
def run(self):
for file in os.listdir():
if file.endswith(".log"):
print(f"Log file - {file}")
self.current_file = open(f"{file}", 'rt')
print(self.current_file.readlines, f"")
self.equally_check()
self.hit_unique_check()
self.current_file.close()
if __name__ == "__main__":
run = ReadFiles()
run.run()
我运行我的 python 代码,但结果总是一样的:“PASS:所有命中都是唯一的。"。对于某些文件,它必须是 "FAIL:这个命中是重复的。“。我不确定方法中的问题hit_unique_check,并且不知道该怎么做。
你能解释一下,我如何才能使这种方法不仅单独正常工作吗?
【问题讨论】:
-
print(self.current_file.readlines, f"")有什么意义?如果你想打印文件中的所有行,那么你需要调用函数.请注意,在你调用该函数后,你的文件句柄将被耗尽,你的循环将不再有效 -
这也是您遇到错误的原因——一旦文件被迭代一次,您需要重新打开它,或者如果您想再次迭代它,则需要重新开始。如果您did any debugging,这将非常明显,尤其是如果您stepped through your code in a debugger
-
也许您应该将该文件读入
run中的列表,然后在您的检查函数中重用该列表。或者,也许您的检查函数应该一次只执行一行,因此您只检查文件一次。
标签: python python-3.x