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
Show 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