根据一个文件夹下图片名称,将对应的另一个文件夹下的xml文件剪切至到新文件夹中。

import os
import shutil

# 图片文件夹路径
image_folder_path = r"D:\Desktop\img"
# txt文件夹路径
txt_folder_path = r"D:\Desktop\xml"
# 新文件夹路径,用于存放剪切过来的文件
new_folder_path = r"D:\Desktop\xml"

# 确保新文件夹存在
if not os.path.exists(new_folder_path):
    os.makedirs(new_folder_path)

# 获取所有图片文件的文件名(不包括扩展名)
image_files = {os.path.splitext(filename)[0] for filename in os.listdir(image_folder_path) if filename.endswith(('.jpg', '.png'))}

# 遍历文本文件夹中的文件
for txt_filename in os.listdir(txt_folder_path):
    if txt_filename.endswith('.xml'):
        # 获取不包括扩展名的文件名
        txt_name_without_ext = os.path.splitext(txt_filename)[0]
        # 检查文件名是否在图片文件名集合中
        if txt_name_without_ext in image_files:
            # 构建源文件和目标文件的完整路径
            txt_path = os.path.join(txt_folder_path, txt_filename)
            new_txt_path = os.path.join(new_folder_path, txt_filename)
            # 剪切文件到新文件夹
            shutil.move(txt_path, new_txt_path)
            print(f"Moved {txt_filename} to {new_folder_path} because a corresponding image file was found.")

# 注意:这段代码会剪切文件,如果需要保留原文件,请使用shutil.copy2代替shutil.move

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值