【问题标题】:How do I not create an infinite loop while reading file lines in Python?在 Python 中读取文件行时如何不创建无限循环?
【发布时间】: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

标签: python loops file


【解决方案1】:

你的意思是为什么程序打印了很多次?如果是这样,您应该删除一个缩进:

def info_count():
    errorLog = open("error_log.txt", "r")
    count = 0
    for line in errorLog:
        if "[info]" in line:
            count += 1
    print(count)

【讨论】:

  • 哇...谢谢。缩进是答案......知道我如何制作另一个函数来获取这些行并输出该行的不同部分吗?即,我希望显示该 IP 地址:[Mon Mar 8 11:45:08 2004] [info] [client 64.242.88.10] (104)Connection reset by peer: client 在发送正文完成之前停止连接
  • 非常感谢。这项工作按预期进行。我必须通读它,看看它在做什么,这样我就可以在不同的情况下复制它。我看到您有一个 YouTube 频道,并计划稍后浏览您的一些作品!
【解决方案2】:

对于 IP 地址(在 cmets 中请求):

import re

def ip():
    error_log = open('error_log.txt','r')
    ip = re.findall('\[client .*?\]', error_log.read())
    print('\n'.join([x[8:-1] for x in ip]))
ip()

方括号是特殊字符,所以我们想告诉python我们只希望它们作为字符串的一部分,为此,在特殊字符之前,我们放一个反斜杠。

* 是告诉 python 我们想要所有[client] 之间的字符。

. 点告诉程序我们接受除换行符之外的 任何 字符。

? 是告诉 python 不要贪婪。例如,假设这是我们的字符串:'Hello, my name is Ann. What is your name?' 我们要查找'm''n' 之间的所有字符。

如果我们的程序是贪婪的,它会给我们['y name is Ann. What is your '],如果不是贪婪,它会给我们['y ', 'e is A']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2013-08-07
    • 1970-01-01
    • 2012-03-27
    相关资源
    最近更新 更多