Emanuele Russo
Emanuele Russo

Reputation: 3

For loop seems to only run once

I have built, as part of a project, a very simple program that checks whether or not a given string is present in a provided text file.

The program checks if the input is equal to each line of the file, using a for loop, and returns True if the values correspond, False if the don't.

with open (names, "r") as file:
    while True: 
        name_check = input("name: ")
        if name_check == "":
            #command to end the program

            break
        for newline in file:
            #compares the input with every line in the txt file

            newline_stripped = newline.lower().strip()
            if newline_stripped == name_check:         

                print (True)
            else:
                print (False)
    file.close()

The issue is, when i run the code, the first iteration works fine, it returns a sequence of False and True as intended, and then asks for another input, however when said input is given again, it immediately asks for another one, without returning any sequence, as if the for loop is being skipped entirely.

I tried running it by using a list of numbers instead of a text file as a source (with proper modification) and it runs 100% as intended, so I suspect it has something to do the way it handles the file itself, but I can't figure out why.

Thanks in advance for any help!

Upvotes: 0

Views: 487

Answers (1)

bereal
bereal

Reputation: 34312

You walk through the entire file on the first iteration, so the second iteration has nothing left to read. You can either open the file on each iteration, or move the position to the start by file.seek(0).

Upvotes: 1

Related Questions