Search code examples
pythondata-extraction

How to handle text file in python


I have a file name called words.txt having Dictionary words in it. I call this file and ask the user to enter a word. Then try to find out whether this word is present in this file or not if yes print True else Word not found.

wordByuser  = input("Type a Word:")
file = open('words.txt', 'r')
    
if wordByuser in file: #or if wordByuser==file:
    print("true")
else:
    print("No word found")

The words.txt files contain each letter in a single line and then the new letter on the second line.


Solution

  • Read the file first, also use snake_case https://www.python.org/dev/peps/pep-0008/

    user_word  = input("Type a Word:")
    with open('words.txt') as f:
        content = f.read()
        if user_word in content:
            print(True)
        else:
            print('Word not found')