Smock
Smock

Reputation: 345

Comparing a word in a list to a word in a file

I'm trying to write a program that loops through a list and checks a file to see if that word is in there. At first, the file is read and then if a word is found, it breaks out of that loop. With the remaining lines in the file after that word is found, I want to compare with the list. The code below isn't working. It just breaks out of the loop and doesn't find the word. Thanks for your assistance.

def readFile():
with open("file.txt", "r") as myfile:
    for line in myfile:
        if "Hello" in line:
            break
    for word in mylist:
        if word in myfile:
           print(word + "found")

Upvotes: 1

Views: 65

Answers (1)

John Kugelman
John Kugelman

Reputation: 361556

You'll need another for line in myfile loop. You can't do if word in myfile to check the entire file, you still need to loop over each line.

with open("file.txt", "r") as myfile:
    for line in myfile:
        if "Hello" in line:
            break
    for line in myfile:
        for word in mylist:
            if word in line:
                print(word + "found")

Note that this could print the same word multiple times. If you don't want that you'll need to track which words you've already seen.

already_seen = set()        

for line in myfile:
    for word in mylist:
        if word in already_seen:
            continue

        if word in line:
            print(word + "found")
            already_seen.add(word)

Upvotes: 2

Related Questions