删除两个路径下的同名文件夹

该Python脚本使用os和shutil模块比较两个目录`dir1`和`dir2`中的文件夹名称,找出共同的文件夹名,然后从目标目录`target_dir`中删除这些同名文件夹。它首先获取每个目录的文件夹列表,找到交集,然后遍历并删除目标目录中的对应文件夹。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

删除两个路径下的同名文件夹

import os
import shutil

def compare_and_delete_folders(dir1, dir2, target_dir):
    # Get a list of folder names in dir1
    folder_names_dir1 = set(next(os.walk(dir1))[1])

    # Get a list of folder names in dir2
    folder_names_dir2 = set(next(os.walk(dir2))[1])

    # Find the common folder names
    common_folder_names = folder_names_dir1.intersection(folder_names_dir2)

    # Delete the folders with the common names from the target directory
    for folder_name in common_folder_names:
        folder_path = os.path.join(target_dir, folder_name)
        if os.path.exists(folder_path):
            shutil.rmtree(folder_path)
            print("delete:"+str(folder_path))

    print("Folders deleted successfully.")

# Provide the directory paths
dir1 = r'D:\BaiduNetdiskDownload\A'
dir2 = r'D:\BaiduNetdiskDownload\B'
target_dir = r'D:\BaiduNetdiskDownload\A'  # Directory to delete the folders from

# Compare the directories and delete the common folders from the target directory
compare_and_delete_folders(dir1, dir2, target_dir)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值