Search code examples
pythontextjupyter-notebookcounter

How to only display the total count of a number of lines without the count being displayed every line?


I have been assigned to find certain lines that contain the word "From:" in a .txt document. I have found all of these, but I am having trouble displaying the total number of lines that contain the word "From:". I have a counter variable in place, but each time I execute the code, the counter is displayed after each line (ex. 1, 2, 3, instead of just 27 at the end of all the output. See picture for reference). Can someone help me fix this?

email_file=open('mbox-short.txt','r')
counter=0
for line in email_file:
    if line.startswith("From:")==True:
        print(line.upper(),end="")
        counter+=1
        print(counter)
email_file.close()

Reference picture


Solution

  • You just need to change the position of the line of code print(counter) to the end so it does not print everytime it loops.

    email_file=open('mbox-short.txt','r')
    counter=0
    for line in email_file:
        if line.startswith("From:")==True:
            print(line.upper(),end="")
            counter+=1
    email_file.close()
    print(counter)