Python修改xml中内容

# coding=utf-8

import numpy as np
import os
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join


#定义xml中字符串转换函数,同理适用于各种文本文件(txt, json等)
def change_xml(xml_path):
    xml_file = open(xml_path, 'r') #以只读的方式读如一个xml文件
    os.remove(xml_path)            #因为后面还要创建同名的xml文件保存修改后的信息,所以此处将原文件删除
    #print(xml_file)
    #while True:
    #line = xml_file.readlines()
    for line in xml_file.readlines():    #readlines方法返回的是一个列表,原文件中每一行是列表中的一个元素,使用for循环遍历每一个元素
        
        #print(line)
        if '<name>left</name>' in line:    #使用replace方法进行内容修改,第一个参数是原始字符串,第二个参数是修改的字符串
            line = line.replace('<name>left</name>', '<name>BSJ</name>')
        elif '<name>a</name>' in line:
            line = line.replace('<name>a</name>', '<name>BSJ</name>')
        elif '<name>mleft</name>' in line:
            line = line.replace('<name>mleft</name>', '<name>MINI</name>')
        elif '<name>mright</name>' in line:
            line = line.replace('<name>mright</name>', '<name>MINI</name>')
        elif '<object>' in line:
            line = line.replace('<object>', '<rectObject>')
        elif '</object>' in line:
            line = line.replace('</object>', '</rectObject>')
            
            
            
        print(line)
        f = open(xml_path,'a')  #创建与之前删除的文件的同名文件
        f.writelines(line)      #将修改后的信息写入文件   
        #f.writelines('\n')
        f.close()               #关闭文件

        #遍历文件夹下的全部xml文件
x = 0
for root, dirs, files in os.walk("/home/edge/darknet-gpu/VOCdevkit-car/VOC2007/Annotations/"):
    #for d in dirs:
        #print(d) #打印子资料夹的个数
    for file in files:
        x = x+1
        #每一个文件的路径
        xml_path = root + file
        #edit_xml(xml_path)
        #调用定义的转换函数
        change_xml(xml_path)

猜你喜欢

转载自blog.csdn.net/qq_35250841/article/details/107317318