Sure! Here's a Python script that scans all files in a specified folder and returns the filenames of those that contain a specific string:
import os
def find_files_with_string(folder_path, search_string):
"""
Scans files in the given folder and returns filenames containing the search string.
:param folder_path: Path to the folder to scan.
:param search_string: String to search for within files.
:return: List of filenames that contain the search string.
"""
matching_files = []
# Walk through all files in the folder (non-recursively)
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# Skip directories
if not os.path.isfile(file_path):
continue
try:
with open(file_path, 'r', encoding='utf-8') as file:
# Read the content and check if string exists
if search_string in file.read():
matching_files.append(filename)
except (UnicodeDecodeError, PermissionError):
# Handle binary files or permission issues gracefully
try:
with open(file_path, 'rb') as file:
content = file.read()
# Search for string as bytes if UTF-8 fails
if search_string.encode('utf-8') in content:
matching_files.append(filename)
except Exception as e:
print(f"Could not read {filename}: {e}")
return matching_files
if __name__ == "__main__":
folder = input("Enter folder path to scan: ").strip()
search_str = input("Enter string to search for: ").strip()
result = find_files_with_string(folder, search_str)
if result:
print("Files containing the string:")
for file in result:
print(f"- {file}")
else:
print("No files contain the specified string.")
🔍 Features:
- Recursively 🔄? This version is non-recursive (only scans top-level files). If you want a recursive version (check subfolders too), let me know!
- Handles 📄 text files and tries to handle 📦 binary files gracefully.
- Reports permission errors and skips unreadable files.
✅ Example usage:
If you have a folder /home/user/docs and you want to find files containing the word "confidential", just run the script and input those values.
Would you like a recursive version as well?