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
根据一个文件夹下图片名称,将对应的另一个文件夹下的xml文件剪切至到新文件夹中。
于 2024-09-25 16:55:53 首次发布