Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unable to read what is the written words using python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading