批量修改voc数据集中xml属性详解

import os
import os.path
import xml.dom.minidom
# C:\\Users\chenlufei\Desktop\\1234.xml

path="F:\\sss\\"        #路径(最好路径下只有xml文件,有其他文件容易报错)
files=os.listdir(path)  #得到文件夹下所有文件名称
s=[]
for xmlFile in files: #遍历文件夹
    if not os.path.isdir(xmlFile): #判断是否是文件夹,不是文件夹才打开
        print (xmlFile)

        #TODO
        #xml文件读取操作

        #将获取的xml文件名送入到dom解析
        dom=xml.dom.minidom.parse(os.path.join(path,xmlFile))  ###最核心的部分os.path.join(path,xmlFile),路径拼接,输入的是具体路径
        root=dom.documentElement
        #获取标签对name/pose之间的值
        name=root.getElementsByTagName('filename')


        #重命名class name
        for i in range(len(name)):
            print (name[i].firstChild.data)
            name[i].firstChild.data='orange'
            print( name[i].firstChild.data)



        #保存修改到xml文件中
        with open(os.path.join(path,xmlFile),'w') as fh:
            dom.writexml(fh)
            print('写入name/pose OK!')


#  with open('dom_write.xml','w',encoding='UTF-8') as fh:
#             # 4.writexml()第一个参数是目标文件对象,第二个参数是根节点的缩进格式,第三个参数是其他子节点的缩进格式,
#             # 第四个参数制定了换行格式,第五个参数制定了xml内容的编码。
#             dom.writexml(fh,indent='',addindent='\t',newl='\n',encoding='UTF-8')
#             print('写入xml OK!')

 

#xml文件中第一行必须为<?xml version="1.0" ?><annotation>,且不能有空格否则报错:
#xml.parsers.expat.ExpatError: XML or text declaration not at start of entity: line 1, column 1

 

https://blog.csdn.net/LOVE1055259415/article/details/79166754

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值