import os import pypdf def search_word_in_folder(folder_path, search_word): """ Searches for a word across all PDF files in a given folder. """ # Normalize the search word for case-insensitive matching search_word_lower = search_word.lower() # Check if the folder exists if not os.path.exists(folder_path): print(f"❌ Error: The folder '{folder_path}' does not exist.") return print(f"Scanning folder '{folder_path}' for '{search_word}'...\n") overall_matches = 0 # Loop through all files in the directory for filename in os.listdir(folder_path): # Only process files that end with .pdf if filename.lower().endswith('.pdf'): pdf_path = os.path.join(folder_path, filename) try: with open(pdf_path, 'rb') as file: reader = pypdf.PdfReader(file) file_has_matches = False # Search page by page for page_num, page in enumerate(reader.pages, start=1): text = page.extract_text() if text and search_word_lower in text.lower(): # Print the filename and page number where found print(f"✅ Found in [{filename}] on Page {page_num}") file_has_matches = True overall_matches += 1 except Exception as e: print(f"⚠️ Could not read file {filename}: {e}") if overall_matches == 0: print("❌ Word not found in any PDF files inside this folder.") else: print(f"\nSearch complete. Total matches found: {overall_matches}") # Example Usage if __name__ == "__main__": # Replace with the path to your folder my_folder = "./my_pdf_documents" word_to_find = "contract" search_word_in_folder(my_folder, word_to_find)