Home > Enterprise >  Why doesn't my counting loop work when searching a phrase in a file?
Why doesn't my counting loop work when searching a phrase in a file?

Time:10-19

I was looking to find how many times the phrase "X-DSPAM-Confidence:" shows up in a file and couldn't figure out why my code wasn't working. I needed to strip the file to only show the lines that contained that phrase, and, in addition, count how many times that phrase shows up. My code was able to strip it properly, but did not count the amount of times the phrase showed up. If anyone could help me figure out what I did wrong with my code that would be greatly appreciated.

enter image description here

CodePudding user response:

It's because you have an extra space in your checker for loop: "X-DSPAM-Confidence: ". Also, you are able to do this inside one for loop as the second one is somewhat redundant.

CodePudding user response:

You can do this just with one loop

count = 0
f = open("")
lines = f.readlines()
for line in f:
    if line.startwith(""): 
        print(line)
        count = count   1

CodePudding user response:

It is because when the first for loop finishes, fh, the read cursor, is at the end of file, so the second for loop actually doesn't read any lines.

Adding fh.seek(0) in between the two loops will solve this problem, as it brings the read cursor back to the beginning of the file.

  • Related