【问题标题】:Program Only Reads the File Once [duplicate]程序只读取一次文件[重复]
【发布时间】:2021-05-25 04:29:41
【问题描述】:

我目前正在尝试编写一个程序来读取文件,并打印任何包含“[ERROR]”或“statistics:”消息的行。该程序将用于查找错误行,但不会找到任何带有统计信息的行。问题是,如果我注释掉查找错误代码的行(使用相同的方法),则统计行完美运行。如果重要的话,这是 Python 3.9.1。有什么想法吗?

def searchFor(word, f):
    print("=" * 75)
    print("Lines containing: ", word)
    print("-" * 50)
    lines = f.readlines()
    for line in lines:
        if word in line:
            print(line)
    print("=" * 75) 

def main():
    f = open("error_log.txt", "r")
    searchFor("[error]", f)
    searchFor("statistics:", f)

main()

【问题讨论】:

标签: python python-3.x file


【解决方案1】:

您可以调用seek()从头开始读取文件:

def searchFor(word, f):
    f.seek(0,0)
    print("=" * 75)
    print("Lines containing: ", word)
    print("-" * 50)
    lines = f.readlines()
    for line in lines:
        if word in line:
            print(line)
    print("=" * 75) 

def main():
    f = open("error_log.txt", "r")
    searchFor("[error]", f)
    searchFor("statistics:", f)

main()

测试日期:

asdfasdf
[error] asdfasdf
[error] 134
statistics: 1111

正确打印:

[error] asdfasdf
[error] 134
statistics: 1111

【讨论】:

    【解决方案2】:

    f 上的第一个函数调用正在使用打开文件的内容并将光标留在文件末尾。当第二个函数调用尝试读取相同的内容时,它认为没有什么可读取的了。

    最好将文件名传递给函数,然后在函数内部处理打开、读取和关闭文件。

    或者,您可以从文件中读取所有行一次,然后将lines 变量传递给每个函数调用。这样可以避免两次读取文件。

    【讨论】:

      猜你喜欢
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 2016-04-05
      • 2011-08-10
      • 2012-07-17
      • 2014-02-12
      • 1970-01-01
      相关资源
      最近更新 更多