Im trying to count how many time the word [error]
is in a file.
This is how my attempt is looking:
with open(r'test.log') as logfile:
for line in logfile:
error = line.count('[error]')
print(error)
The outcome of this result a list like this:
0
1
1
0
1
etc. I want the outcome to be "Error 10" or how many times the word occur
CodePudding user response:
count = 0
with open('test.log', 'r') as logfile:
lines = logfile.readlines()
for line in lines:
count = line.count('[error]')
print(count)
CodePudding user response:
What I believe is happening is the loop is printing how many errors are in each line every time it loops. What you might want to do is have an external variable outside the loop that the loop adds to to find the total sum.
error_count = 0
with open(r'test.log') as logfile:
for line in logfile:
error_count = line.count('[error]')
print("error" str(error_count))