How do I find a word in a text file Python?

How do I find a word in a text file Python?

To find or check if a word exists in a file or not and if it exists get its location - following code can be used .

if "".join(open("filname.txt", "r").readlines()).find(word) != -1:
    print("Word Found")
else:
    print("Not found")

Explanation

open("filename.txt", "r") opens the file in readmode. readlines() method reads the lines from file.

Now we have a list, we can use join() method to convert the list into a string.

Now we have a string, we can simply use find() method check if required word exists in the file or not.

find() method returns -1 if desired word is not found else the first index of string in whole text file.



Comments