Friday 9 February 2024

Python File Word Search Program

Python File - Word Search Program

This file management functions searches for a specific word in a text file.
  • Reads the file line by line and checks for word presence.
  • Prints whether the word was found or not.

# Open the file in read mode
file = open("students.txt", "r")

# Get the word to search from the user
word_to_search = input("Enter the word to search: ")

# Initialize a flag to indicate if the word is found
word_found = False

# Read the file line by line
for line in file:
    # Remove leading and trailing whitespace
    line = line.strip()

    # Split the line into words
    words = line.split()

    # Check if the word is present in the current line
    if word_to_search in words:
        word_found = True
        print("Word found")
        break  # Stop searching once the word is found

# If the word is not found, print a message
if not word_found:
    print("Word not found in the file.")

Output of program:

Enter the word to search: amit
Word found

Following is the content of students.txt file.

NAME AGE ADDRESS

amit 24 usa

sunit 26 canada

kuntal 25 india

bhavin 27 india


* * * * * 


Program Using User Defined Functions


def search_word(filename, word):
    try:
        with open(filename, "r") as f:
            found = False
            for line in f:
                if word in line.lower():
                    found = True
                    break
        if found:
            print(f"Word '{word}' found in {filename}")
        else:
            print(f"Word '{word}' not found in {filename}")
    except FileNotFoundError:
        print("File not found!")

if __name__ == "__main__":
    filename = input("Enter file name: ")
    word = input("Enter word to search: ")
    search_word(filename, word)

Output of program:

Enter file name: products.txt
Enter word to search: pen
Word 'pen' found in products.txt


Note: I have saved this python program and a products.txt file in same folder.

Content of products.txt file.

pen,10,50

pencil,20,25 

sketchbook,20,10

notebook,10,30


* * * * *