0

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
AppleCider
  • 39
  • 4
  • 3
    Do you mean to be printing out the whole file for every iterable in the file? Seems like `print(i)` might be what you want instead. – BTables Jan 20 '22 at 15:11
  • 2
    You are iterating over a string containing all the text in the file and printing whole file for every single character in that string. – matszwecja Jan 20 '22 at 15:12
  • `i` is never going to be anything other than a single character. – Axe319 Jan 20 '22 at 15:12

2 Answers2

2

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
S4eed3sm
  • 1,398
  • 5
  • 20
1

before, you should split the lines b/c it will loop into the string and check if the characters are ffff, and it won't be True

i will be a single character, so you should do first

dictionary = dictionary.split("\n")

BUT if your ffff is a line, if is a word separated with spaces you can do:

dictionary = dictionary.split(" ")
XxJames07-
  • 1,833
  • 1
  • 4
  • 17