【发布时间】:2020-05-21 03:41:15
【问题描述】:
我环顾四周,但无法弄清楚为什么我的第三个函数 info_count() 在无限循环中运行:
def error_statement():
errorLog = open("error_log.txt", "r")
for line in errorLog:
if "[error]" in line:
print(line)
def statistics_statement():
errorLog = open("error_log.txt", "r")
for line in errorLog:
if "statistics" in line:
print(line)
def info_count():
errorLog = open("error_log.txt", "r")
count = 0
for line in errorLog:
if "[info]" in line:
count += 1
print(count)
error_statement()
statistics_statement()
info_count()
前两个返回正确的结果并结束。但是我的计数一直在循环,我不明白为什么它在运行结束时没有中断。
此外,一旦我得到了这个计数,我想稍后打印这些行,但只打印一个特定的部分,即 IP 地址,它可能在返回“[info]”的每一行上有所不同。请指教。
【问题讨论】:
-
你能发布部分输出吗?
-
在
info_count()中,print(count) 在 for 循环中。您可能想在循环外打印计数,然后发布示例输出? -
@AnnZen output: 0 0 0 0 0 1 1 2 2 2 2 2 2 ... 超过 2 不算,但会继续。
-
最好在每个函数中关闭文件。
-
为什么不把
errorLog = open("error_log.txt", "r")改成with open("error_log.txt", "r") as errorLog?