修改xml中的类别名

内含xml中修改类别名和删除类别名

import xml.etree.ElementTree as ET
import os
import shutil
path_all = 'xxxxxx' #xml路径
dir_list = os.listdir(path_all)
def get_and_check(root, name, length):
    vars = root.findall(name)
    if len(vars) == 0:
        raise NotImplementedError('Can not fing %s in %s.' % (name, root.tag))
    if length > 0 and len(vars) != length:
        raise NotImplementedError('The size of %s is supposed to be %d, but is %d.' % (name, length, len(vars)))
    if length == 1:
        vars = vars[0]
    return vars
category_list = []
targe_list = []
for xml_i in dir_list:
    if 'xml' in xml_i:
        file_path = os.path.join(dir_list, xml_i)
        try:
            tree = ET.parse(file_path)
            root = tree.getroot()
            for obj in root.findall('object'):
                category = get_and_check(obj, 'name', 1).text
                if category == 'xxx': #待修改类别名
                   obj.find('name').text = 'xxx' #修改类别
                if category == 'xxx': # 待删除类别名
                   root.remove(obj)    #删除
                tree.write(os.path.join(dir_list, xml_i))
    
        
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值