Find a Word in a Text file using Python ready-to-use function

How to find a Word in a Text file using Python ready-to-use function?

Ready to use Python function to find a word in a text file:

def find_string_in_text_file(txtFile, findWord, case_sensitive=False):
    # Check if 'findWord' string exists in text file
    with open(txtFile, 'r') as file:
        lines = file.readlines()
        for row in lines:
            # remove new line character if exists
            row = row.replace("\n", "")
            # change to loawer case if case senstive is false
            if case_sensitive == False:
                row = row.lower()
                findWord = findWord.lower()
            # Check string is matching and length of the strings are matching
            if row.find(findWord) >= 0:
                return True
        return False # if no match, return False

Write your main code as a sample below, and save a text file named ‘test python.txt’ in the same directory by the inclusion of the word ‘request’ in the text file.

print(find_word_in_text_file("test python.txt", "request"))

The output of the code is,


How does the function work?

This code defines a function named “find_string_in_text_file”. The function takes three arguments:

  1. The txtFile: The name of the text file that needs to be searched.
  2. The findWord: The string that needs to be searched in the text file.
  3. The case_sensitive: A boolean value that determines if the search should be case-sensitive or not. If it’s set to False, the code will search for the string in a case-insensitive manner.

The function uses the with open statement to open the text file specified in the txtFile argument. It then reads all the lines of the file using the readlines method and stores the lines in a list called lines.

Next, the code uses a for loop to iterate through each line in the lines list. For each line, it removes the newline character (if it exists) using the replace method and converts the line to lowercase if the case_sensitive argument is set to False. This ensures that the search for the string is case-insensitive.

The find method is then used to check if the findWord string is present in the current line. If the find method returns a value greater than or equal to 0, it means that the string was found, and the function returns True.

If the loop completes without finding a match, the function returns False, indicating that the string was not found in the text file.

Leave a Reply

Your email address will not be published. Required fields are marked *