Of course! Here are a few versions of a Python script to do this, starting with a simple one and building up to a more robust and flexible command-line tool.
Option 1: Simple & Straightforward Script
This is the most basic version. You edit the folder_to_scan and string_to_find variables directly in the script.
Code:
python
import os
def find_files_with_string(folder_path, search_string):
"""
Scans files in a given folder and returns a list of filenames
that contain the specified string.
Args:
folder_path (str): The path to the folder to scan.
search_string (str): The string to search for within the files.
Returns:
list: A list of filenames (not full paths) that contain the string.
"""
found_files = []
# Check if the folder path is valid
if not os.path.isdir(folder_path):
print(f"Error: Folder not found at '{folder_path}'")
return found_files
# Iterate over all entries in the folder
for entry in os.scandir(folder_path):
# Check if the entry is a file
if entry.is_file():
try:
# Open and read the file
with open(entry.path, 'r', encoding='utf-8', errors='ignore') as f:
# Check if the search string is in the file's content
if search_string in f.read():
found_files.append(entry.name)
except Exception as e:
# This can happen for various reasons, e.g., permission errors
print(f"Could not read file {entry.name}: {e}")
return found_files
# --- Main part of the script ---
if __name__ == "__main__":
# --- CONFIGURE YOUR SEARCH HERE ---
folder_to_scan = '.' # Use '.' for the current directory
string_to_find = 'import'
# ----------------------------------
print(f"Scanning folder '{os.path.abspath(folder_to_scan)}' for string: '{string_to_find}'\n")
matching_files = find_files_with_string(folder_to_scan, string_to_find)
if matching_files:
print("Found string in the following files:")
for filename in matching_files:
print(f"- {filename}")
else:
print("No files found containing the string.")
How to Use:
Save the code as a Python file (e.g., find_string.py).
Change the folder_to_scan and string_to_find variables to your desired values.
Run the script from your terminal: python find_string.py
Option 2: Advanced Command-Line Tool
This version is much more flexible. You can specify the folder, search string, and other options (like recursive search) directly from the command line without editing the script. It uses Python's argparse module.
Features:
Specify folder and string via command-line arguments.
Recursive search: Scan subfolders too.
Case-insensitive search.
Returns full paths for clarity, especially in recursive mode.
Code:
python
import os
import argparse
def search_in_file(file_path, search_string, ignore_case):
"""Checks if a string exists in a single file."""
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
# For large files, it's more memory-efficient to read line-by-line
for line in f:
if ignore_case:
if search_string.lower() in line.lower():
return True
else:
if search_string in line:
return True
except (IOError, OSError) as e:
# This handles file permission errors, etc.
# print(f"Warning: Could not read file {file_path}: {e}")
pass # Silently ignore files we can't read
return False
def scan_directory(root_folder, search_string, recursive, ignore_case):
"""
Scans a directory for files containing a specific string.
"""
found_files = []
if not os.path.isdir(root_folder):
print(f"Error: Directory not found at '{root_folder}'")
return found_files
print(f"Scanning '{os.path.abspath(root_folder)}'...")
# Use os.walk for recursive search, otherwise use os.scandir for single level
if recursive:
for dirpath, _, filenames in os.walk(root_folder):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
if search_in_file(file_path, search_string, ignore_case):
found_files.append(file_path)
else:
for entry in os.scandir(root_folder):
if entry.is_file():
if search_in_file(entry.path, search_string, ignore_case):
found_files.append(entry.path)
return found_files
def main():
"""Main function to parse arguments and run the scan."""
parser = argparse.ArgumentParser(
description="Scan files in a folder and find those containing a specific string.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("search_string", help="The string to search for.")
parser.add_argument("folder_path", nargs='?', default='.',
help="The path to the folder to scan (default: current directory).")
parser.add_argument("-r", "--recursive", action="store_true",
help="Scan directories and subdirectories recursively.")
parser.add_argument("-i", "--ignore-case", action="store_true",
help="Perform a case-insensitive search.")
args = parser.parse_args()
matching_files = scan_directory(args.folder_path, args.search_string, args.recursive, args.ignore_case)
if matching_files:
print("\n[+] Found matches in the following files:")
for file_path in matching_files:
print(f" - {file_path}")
else:
print("\n[-] No files found containing the specified string.")
if __name__ == "__main__":
main()
How to Use:
Save the code as a Python file (e.g., search_tool.py).
Open your terminal or command prompt.
Run the script with arguments.
Examples:
Search for "ERROR" in the current directory (.):
bash
python search_tool.py "ERROR" .
Search for "TODO" in a specific directory (case-insensitive):