user3238952
user3238952

Reputation: 3

Element not in a list with Python 3

I'm using Python 3, what I want is to identify whether a word is in a text file or not.

Content of the text file:

test
test
test

My code:

    wordsUsedFilename = "usedwords.txt"
f = open(wordsUsedFilename, 'r')
usedWords = [line.strip() for line in f]
words = []
words.append("test")
check = True
while check:
    for word in words:
        if word not in usedWords:
            print("Not in the list") 
        else:
            print("In the list")
            check = False

The problem is that the program should stop but it keeps running considering that the word is not in the list, what did I did wrong ?

Upvotes: 0

Views: 74

Answers (2)

monkut
monkut

Reputation: 43840

For what you seem to be doing you can just check against the whole block of data.

wordsUsedFilename = "usedwords.txt"
words = ["test"]
f = open(wordsUsedFilename, 'r')
text= f.read()
for word in words:
    if word in text:
        print("{} in {}".format(word, wordsUsedFilename))

Upvotes: 0

Mike DeSimone
Mike DeSimone

Reputation: 42805

Your problem is here:

f = open(wordsUsedFilename, 'a+')

The 'a+' mode appends to the end of the file... which is where it starts reading from the file as well. Change it to 'r' and you're golden.

P.S. You're better off using set to store the word list:

usedWords = set()
with open(wordsUsedFilename, 'r') as f:
    for line in f:
        usedWords.add(line.strip())

Here's the whole thing:

wordsUsedFilename = "usedwords.txt"
usedWords = set()
with open(wordsUsedFilename, 'r') as f:
    for line in f:
        usedWords.add(line.strip())
words = []
words.append("test")
for word in words:
    if word not in usedWords:
        print("Not in the list") 
    else:
        print("In the list")

And it works for me:

$ more usedwords.txt 
test
test
test
$ python practice.py 
In the list

Upvotes: 1

Related Questions