-1

I'm currently trying to write a program to read through a file, and print any lines that contain an "[ERROR]" or "statistics:" message. The program will work for finding error lines, but will not find any lines with statistics. The thing is that if I comment out the line that looks for error codes (using the same method), the statistics line works perfectly. This is Python 3.9.1 if that matters. Any thoughts?

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()

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880

2 Answers2

0

You can invoke seek() to restart reading the file from the beginning:

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()

Tested on:

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

Correctly prints:

[error] asdfasdf
[error] 134
statistics: 1111
Joris Kinable
  • 2,232
  • 18
  • 29
0

The first function call on f is consuming the contents of the open file and leaving the cursor at the end of the file. When the second function call tries to read the same content, it thinks there's nothing left to read.

It would be better to pass the file name to the function, then handle opening, reading, and closing the file inside the function.

Alternatively, you could read all of the lines from the file once, then pass the lines variable to each function call. This would avoid reading the file twice.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880