import osimport uuid# Initialize a list to store files containing the keywordcontains = []# Generate a unique identifier for this search session (not currently used)id_ = uuid.uuid4()# List of file extensions to search withinextensions = [".txt", ".docx", ".pdf"]def change_direct():# Prompt the user to enter the directory pathpath = input("Enter path: ")# Prompt the user to enter the keyword or phrase to search forkeyword = input("Keyword/Phrase: ")# Start searching the specified foldersearch_folder(path, keyword)def search_folder(path, keyword):global contains # Declare the global variable to store found files# Check if the given path is a directoryif os.path.isdir(path):# List all files and directories in the specified pathfiles = os.listdir(path)# Iterate over each file in the directoryfor file in files:# Construct the full path to the file or directoryfull_path = os.path.join(path, file)# If the current path is a directory, recursively search inside itif os.path.isdir(full_path):search_folder(full_path, keyword)else:# Get the file extension and convert it to lowercasefiletype = os.path.splitext(file)[-1].lower()# Check if the file type is in the allowed extensionsif filetype in extensions:try:# Open the file and read its contentwith open(full_path, 'r', encoding='utf-8', errors='ignore') as file_:# Check if the keyword is found in the file contentif keyword in file_.read():contains.append(file) # Add the file to the list of found filesprint(keyword, "found in", file) # Print the resultexcept Exception as e:# Print any errors encountered while reading the fileprint(f"Error reading {full_path}: {e}")else:# Print an error message if the provided path is not a directoryprint(f"{path} is not a directory.")# Start the process by calling the change_direct functionchange_direct()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。