0

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))
  • Could you add sample xml input and expected xml output? – Cole Tierney Mar 20 '20 at 21:17
  • _But it's throwing error._ What error? What is your question, exactly? Stack Overflow is not a free code writing service, nor is it meant to provide personalized guides and tutorials. See: [ask], [help/on-topic], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users. – AMC Mar 20 '20 at 22:41
  • Also, don't use a bare `except` like that, see https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except. – AMC Mar 20 '20 at 22:42

1 Answers1

0

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)
msh_bl
  • 1
  • 1