简体   繁体   中英

How to Modify Multiple .xml files of one folder and save them to another?

There are hundreds of .xml files. I need to change the .xml files and save with the same name in diff folders.

There are many objects with the same name. Need to change all.

-<object>

<name>hat</name>

<pose>Unspecified</pose>

<truncated>0</truncated>

<difficult>0</difficult>

This is the code I have written in Python. But it's throwing error.

import xml.etree.ElementTree as ET
import os

path = "S:/try" # Source Folder
dstpath = "S:/try1"

try:
    makedirs(dstpath)
except:
    print ("Directory already exist")

for filename in os.listdir(path):
    if filename.endswith('.xml'):
        tree = ET.parse(filename)
        root = tree.getroot()
        for name in root.iter('name'):
            name.text = str('helmet')
        tree.write('%s/%s'%(distpath,filename))

I think the ET.parse command needs full path of the XML files in the for loop. So you can try this:

import xml.etree.ElementTree as ET
import os

path = "/your/original/XMLpath" #Source 
dstpath = "/your/newfiles/XMLpath" #save as XML in different folder

for filename in os.listdir(path):
    if filename.endswith('.xml'):
        tree = ET.parse(path+"/"+filename) #full path of the XML file with it's name
        root = tree.getroot()
        for node in root.iter('name'):
            node.text = 'newname'
        save = dstpath+filename
        tree.write(save)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM