找出两个指定文件夹中文件名不同(忽略后缀)的文件,并删除

import os

def get_file_name_without_extension(file_name):
    # 移除文件的后缀名,返回文件名
    return os.path.splitext(file_name)[0]

def find_and_delete_unmatched_files(folder1, folder2):
    # 获取两个文件夹中的文件名(忽略后缀)
    files1 = {get_file_name_without_extension(file) for file in os.listdir(folder1) if os.path.isfile(os.path.join(folder1, file))}
    files2 = {get_file_name_without_extension(file) for file in os.listdir(folder2) if os.path.isfile(os.path.join(folder2, file))}

    # 找出两个文件夹中不匹配的文件名
    unmatched_in_folder1 = files1 - files2
    unmatched_in_folder2 = files2 - files1

    # 删除第一个文件夹中不匹配的文件
    for unmatched in unmatched_in_folder1:
        for file in os.listdir(folder1):
            if get_file_name_without_extension(file) == unmatched:
                os.remove(os.path.join(folder1, file))
                print(f"Deleted {os.path.join(folder1, file)}")

    # 删除第二个文件夹中不匹配的文件
    for unmatched in unmatched_in_folder2:
        for file in os.listdir(folder2):
            if get_file_name_without_extension(file) == unmatched:
                os.remove(os.path.join(folder2, file))
                print(f"Deleted {os.path.join(folder2, file)}")

# # 替换以下路径为你的两个文件夹路径
folder1_path = 'E:\Data\img\ddc/0613\img'
folder2_path = 'E:\Data\img\ddc/0613/txt'
find_and_delete_unmatched_files(folder1_path, folder2_path)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值