Python Forum

Full Version: Searching for specific word in text files.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I search in a file for a specific word? It should ignore word containing that word, for example.

word to search = 'ello'
text file -
hello
there
It shouldn't output anything file with the above text file
hello
ello
there
It should output 'success' with the above text file. How could I do this?
my_string = "hello\nthere"
print(my_string)

start_index = my_string.find("ello")
print(start_index)

start_index = my_string.find("x")
print(start_index)
Opening files in text-mode for reading: https://docs.python.org/3/library/functions.html#open
Together with Context-Manager: https://realpython.com/working-with-file...as-pattern

All together in a function:

def has_pattern(file, pattern):
    with open(file, encoding="utf8") as fd:
        # inside this block the file is open for reading
        # read content -> find pattern -> return result_of_pattern != -1
        return fd.read().find(pattern) != -1