以下代码用于合并xml文件
将b文件夹内的所有xml文件合并到a文件夹中的xml文件中,这两个文件夹的所有对应的xml文件名字都一样,现在要将b文件夹中和a文件夹中名字相同的xml文件中包含<name>cntr</name>的 <object>添加到a文件夹对应名字的xml中 其他的<object>不用管
其中cntr可更换 主要用于扩充数据集时打的新标签和之前的合并起来
import os
import xml.etree.ElementTree as ET
import shutil
import xml.dom.minidom as minidom
# 定义a和b文件夹路径
a_folder = 'a'
b_folder = 'b'
# 获取a文件夹和b文件夹中的所有xml文件名
a_files = os.listdir(a_folder)
b_files = os.listdir(b_folder)
# 遍历文件夹中的xml文件
for file_name in a_files:
if file_name in b_files:
a_file_path = os.path.join(a_folder, file_name)
b_file_path = os.path.join(b_folder, file_name)
# 解析a文件夹中的xml文件
a_tree = ET.parse(a_file_path)
a_root = a_tree.getroot()
# 解析b文件夹中的xml文件
b_tree = ET.parse(b_file_path)
b_root = b_tree.getroot()
# 查找包含特定内容的<object>标签
for b_object in b_root.findall(".//object[name='cntr']"):
# 检查a文件夹中是否已存在相同的<object>标签
object_exists = False
for existing_object in a_root.findall(".//object"):
# 逐个属性比较两个<object>标签
if all(existing_object.find(attr).text == b_object.find(attr).text for attr in ['name', 'pose', 'truncated', 'difficult']):
# 如果两个<object>标签相同,则继续比较<bndbox>标签的内容
a_bndbox = existing_object.find("bndbox")
b_bndbox = b_object.find("bndbox")
if all(a_bndbox.find(coord).text == b_bndbox.find(coord).text for coord in ['xmin', 'ymin', 'xmax', 'ymax']):
# 如果两个<bndbox>标签的内容也相同,则设置object_exists为True并跳出循环
object_exists = True
break
# 如果a文件夹中不存在相同的<object>标签,则将b文件夹中的<object>标签添加到a文件夹对应的xml中
if not object_exists:
a_root.append(b_object)
# 将修改后的内容写入一个临时文件
temp_file_path = "temp.xml"
a_tree.write(temp_file_path)
# 使用minidom解析临时文件,设置缩进和格式,并删除空行
temp_tree = minidom.parse(temp_file_path)
formatted_xml = "\n".join([line for line in temp_tree.toprettyxml(indent=" ").split("\n") if line.strip()])
# 将格式化后的XML写入a文件夹中的xml文件
with open(a_file_path, "w") as f:
f.write(formatted_xml)
# 删除临时文件
os.remove(temp_file_path)
# 完成后可以将b文件夹中的文件移动或删除
# shutil.rmtree(b_folder) # 删除b文件夹中的文件