File Search Operations - Python Programming Exercise

In this exercise, you will develop a Python program that searches for a specific word or phrase within a text file. This exercise is perfect for practicing file handling, string manipulation, and error handling in Python. By implementing this program, you will gain hands-on experience in handling file operations, string manipulation, and error handling in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Memory Management Techniques

 Exercise

File Search Operations

 Objective

Develop a Python program that searches for a specific word or phrase within a text file. The program should allow the user to input the word or phrase they wish to search for and return all lines containing that word or phrase. Additionally, the program should handle scenarios where the file is not found or when no matches are found, providing appropriate feedback to the user.

 Example Python Exercise

 Copy Python Code
def search_in_file(file_path, search_text):
    """Search for the given text in the specified file and return matching lines."""
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            matches = [line.strip() for line in lines if search_text.lower() in line.lower()]
            
            if matches:
                return matches
            else:
                return None
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
        return None
    except Exception as e:
        print(f"An error occurred: {e}")
        return None


def main():
    # Get the file path and search text from the user
    file_path = input("Enter the path of the text file: ")
    search_text = input("Enter the word or phrase to search for: ")

    # Perform the search
    result = search_in_file(file_path, search_text)

    # Display results
    if result is not None:
        if result:
            print(f"\nLines containing '{search_text}':")
            for line in result:
                print(line)
        else:
            print(f"No lines found containing '{search_text}'.")
    else:
        print("No results to display.")


# Run the program
if __name__ == "__main__":
    main()

 Output

Enter the path of the text file: example.txt
Enter the word or phrase to search for: Python

Lines containing 'Python':
Python is a great programming language.
I am learning Python for data science.

 Share this Python Exercise

 More Python Programming Exercises of Memory Management Techniques

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Implementing a Queue Using List

    In this exercise, you will develop a Python program to implement a queue using a list. This exercise is perfect for practicing data structures, list manipulati...

  •  Building a Stack Using Lists

    In this exercise, you will develop a Python program to implement a stack using a list. This exercise is perfect for practicing data structures, list manipulati...

  •  Working with Queue Collections

    In this exercise, you will develop a Python program to demonstrate the use of queue collections. This exercise is perfect for practicing data structures, queue...

  •  Queue and Stack for Reverse Polish Notation

    In this exercise, you will develop a Python program to evaluate expressions written in Reverse Polish Notation (RPN) using a queue and stack. This exercise is ...

  •  Working with ArrayList

    In this exercise, you will develop a Python program to demonstrate the use of an ArrayList-like structure. This exercise is perfect for practicing data structu...

  •  ArrayList Copying a Text File

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to duplicate the contents of a text file. This exercise is p...