If i manually key the words in the txt and run the program the "word found" can be displayed but when i run python for the new words it shows up in the text file but it does not display "word found" when i run it for a second time. Any idea for this?
word = input("Please enter a word: " ).lower()
dictionary = open("Dictionary.txt","r")
if word in dictionary:
print("word found")
else:
dictionary = open("Dictionary.txt","a")
dictionary.write(word)
dictionary.write("\nThis sentence contains" + " " + word)
dictionary.close()
>Solution :
You have a few things you need to be careful of. I made an assumption to get a working example that the words are stored on individual lines. I also read them in and remove and leading or trailing whitespace so the match can work
word = input("Please enter a word: ").lower()
dictionary = open("Dictionary.txt", "r")
words = [x.strip() for x in dictionary.readlines()]
if word in words:
print("word found")
else:
appending_handle = open("Dictionary.txt", "a")
appending_handle.write("\n" + word)
appending_handle.close()
dictionary.close()
I also made a new variable to store the second dictionary open. Otherwise you will never close the original because you’ve lost the reference.
It’s also not clear you want to do this at all
dictionary.write("\nThis sentence contains" + " " + word)
since it adds these to the dictionary