pythonloopsfilefor-loopctf

Why does my for loop run indefinitely and doesn't stop when the if condition is met?


I'm trying to read text from a file and using a loop to find a specific text from the file. The data in the file is listed vertically word by word. When I run the script, after it prints the last word in the file it repeats itself from the beginning indefinitely.

with open('dictionary.txt','r') as file:
    dictionary = file.read().strip()
for i in dictionary:
 print (dictionary)
 if( i == "ffff" ):
    break

Solution

  • first split the lines by "\n" then print(i) not print(dictionary):

    with open('dictionary.txt', 'r') as file:
        dictionary = file.read().strip().split("\n")
    for i in dictionary:
        print(i)
        if i == "ffff":
            break