酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

用python写一份完整可实行的代码,具体功能如下。1:选择目录。2:选择txt文件。3:将txt文件内的每行文字与目录的所有文件夹匹配,匹配成功则删除该文件夹,默认匹配度在100%才可以删除。

为了实现你的需求,我们可以编写一个Python脚本,它可以完成以下功能: 1. 允许用户选择目录。 2. 允许用户选择一个txt文件,其中包含要匹配和删除的文件夹名称。 3. 程序将逐行读取txt文件中的每个文件夹名称,并在指定目录中查找匹配的文件夹。如果找到匹配的文件夹且匹配度为100%,则删除该文件夹及其内容。 以下是实现这些功能的Python代码示例: ```python import os import shutil def match_and_delete_folders(directory, txt_file): # Step 1: Read folder names from the txt file with open(txt_file, 'r', encoding='utf-8') as file: folders_to_delete = [line.strip() for line in file.readlines() if line.strip()] # Step 2: Traverse the specified directory and delete matching folders for root, dirs, files in os.walk(directory, topdown=False): for folder in dirs: folder_path = os.path.join(root, folder) if folder in folders_to_delete: # Check if folder matches exactly (100% match) if folder == os.path.basename(folder_path): print(f"Deleting folder: {folder_path}") shutil.rmtree(folder_path) else: print(f"Skipping partial match: {folder_path}") if __name__ == "__main__": # Step 3: User input for directory and txt file chosen_directory = input("Enter the directory path to search: ").strip() txt_file_path = input("Enter the path to the txt file containing folder names: ").strip() # Step 4: Call the function to match and delete folders match_and_delete_folders(chosen_directory, txt_file_path) ``` 使用说明: - 运行该脚本后,程序会要求用户输入要搜索的目录路径和包含要删除文件夹名称的txt文件路径。 - 脚本将逐行读取txt文件,然后在指定的目录中搜索每个文件夹名称。 - 如果找到完全匹配(文件夹名称与txt文件中的一行完全相同),则删除该文件夹及其内容。 请确保在使用该脚本时,你已经备份了重要数据,因为删除操作是不可逆的。 [2024-06-28 17:33:36 | AI写代码神器 | 1280点数解答]

相关提问