xml文件存在没有object根目录的情况进行删除

调用其他库可能存在无法解析的情况,根据xml文件中,annotation标签下的根目录判断是否存在object,并结合对应图片进行删除

import xml.dom.minidom
import os
path = r'E:\busandstation_data\Annotations'  # xml文件存放路径
# sv_path = r'D:\coco_unzip\myxmlsave'  # 修改后的xml文件存放路径
image_path = r'E:\busandstation_data\JPEGImages'  # img文件存放路径
img_name = os.listdir(image_path)
files = os.listdir(path)
count = 1
for xmlFile in files:
        # 加载xml文件到内存中
    dom = xml.dom.minidom.parse(os.path.join(path, xmlFile))  # 打开xml文件,送到dom解析
    # 获取根节点信息
    annotation = dom.getElementsByTagName('annotation')
    # 打印的结果是只有一个数据的列表   annotation = [<DOM Element: annotation at 0x1ffcd0ad310>]
    # 判断文件中是否存在annotation节点
    if annotation and len(annotation) > 0:
        # 根据tag名,从annotation中获取所有的tag=object的节点列表
        # 从annotation的打印信息可以看出,通过getElementsByTagName获取到的数据都是列表,所以需要使用annotation[0]
        annotationList = annotation[0].getElementsByTagName('object')
        if annotationList == []:
            count += 1
#             os.remove(os.path.join(path,xmlFile))
            # dom = xml.dom.minidom.parse(r'D:\coco_unzip\mybulidvoc_annotation\000000000724.xml')  # 打开xml文件,送到dom解析
            # root = dom.documentElement  # 得到文档元素对象
            # item = root.getElementsByTagName('name')  # 获取filename这一node名字及相关属性值
            # 获取根节点信息
            annotation = dom.getElementsByTagName('annotation')
            # 打印的结果是只有一个数据的列表   annotation = [<DOM Element: annotation at 0x1ffcd0ad310>]
            # 判断文件中是否存在annotation节点
            if annotation and len(annotation) > 0:
                # 根据tag名,从annotation中获取所有的tag=object的节点列表
                # 从annotation的打印信息可以看出,通过getElementsByTagName获取到的数据都是列表,所以需要使用annotation[0]
                filename = annotation[0].getElementsByTagName('filename')
                address = filename[0].firstChild.data
                print(address)
                new_name = address + '.jpg'
                os.remove(os.path.join(path,xmlFile))
                os.remove(os.path.join(image_path,new_name))
        else:
            print(False)
print(count)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值