find value (specific words) inside files with specific extension in nested folders python
- User
find value (specific words) inside files with specific extension in nested folders python
- Assistant
find value (specific words) inside files with specific extension in nested folders python
To find specific words in files with a certain extension within nested folders using Python, you can use the os module to traverse the directory tree, and the open() function to read the contents of the files. A simple and straightforward way to implement this is by defining a function that iterates through each file, checks its extension, reads its content, and searches for the specific words.
Here's a step-by-step guide with a Python script to accomplish this:
import os
def find_words_in_files(root_dir, file_extension, search_words):
"""
Search for specific words in files with a specific extension within a directory tree.
:param root_dir: The directory to search within.
:param file_extension: The file extension to look for.
:param search_words: List of words to search for in the files.
"""
# Normalize the file extension to ensure it starts with a dot
if not file_extension.startswith('.'):
file_extension = '.' + file_extension
# Normalize search words to lowercase for case insensitive search
search_words = [word.lower() for word in search_words]
# Walk through the directory tree
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
if filename.endswith(file_stmtension):
file_path = os.path.join(dirpath, filename)
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read().lower() # Read and convert content to lowercase
# Check for each word in the content
found_words = [word for word in search_words if word in content]
if found_words:
print(f"Found words {found_words} in {file_path}")
except Exception as e:
print(f"Failed to read {file_path}: {e}")
# Example usage:
root_directory = '/path/to/your/directory'
file_ext = '.txt' # Search for text files
words_to_find = ['example', 'test', 'word']
find_words_in_files(root_directory, file_ext, words_to_find)
Directory Traversal (os.walk()): This function walks through the directory tree starting from root_dir. It yields a tuple with the current path (dirpath), directories in dirpath (dirnames), and filenames in dirpath (filenames).
File Extension Check & Open Files: The script checks if the current file ends with the specified extension. If it does, the file is opened, and its contents are read.
Search for Words: The content of each file is converted to lowercase to perform a case-insensitive search. The script then checks if any of the specified words are in the content. Found words are printed along with their file path.
Error Handling: Opening a file might fail (due to permissions issues, file being a directory, etc.), so an exception handling block (try-except) is used to manage any exceptions that arise.
This script provides a basic structure for searching words in files of a specific type within a directory and its subdirectories. It can be extended or modified based on more specific needs, such as regular expressions searching or complex text processing requirements.
Not yet included in a published release.