利用ElementTree对xml进行修改

# coding:utf-8
# Copyright@hitzym, Dec,09,2017 at HIT
# blog:http://blog.csdn.net/yinhuan1649/article/category/7330626
import os
import xml.etree.ElementTree as ET

xmlpath = './srcxml/'
new_xmlpath = './newxml/'
for i in os.listdir(xmlpath):
    a, b = os.path.splitext(i)
    tree = ET.parse(xmlpath+a+'.xml')
    root = tree.getroot()
    for name in root.iter('filename'):
        older_name = str(name.text)
        new_name = older_name+'.jpg'
        name.text = str(new_name)
    tree.write(new_xmlpath + a + '.xml')
    print str(i) + ' has been modified! :)'

原xml文件中文件名没带后缀.jpg,经修改后加上.jpg
原xml:

<annotation verified="no">
  <folder>zym-jpg</folder>
  <filename>0010</filename>
</annotation>

新xml:

<annotation verified="no">
  <folder>zym-jpg</folder>
  <filename>0010.jpg</filename>
</annotation>  

猜你喜欢

转载自blog.csdn.net/yinhuan1649/article/details/78818166