![](/img/trans.png)
[英]How to take all files from a folder as input (one at a time) and save them into another folder after processing?
[英]How to Modify Multiple .xml files of one folder and save them to another?
有數百個 .xml 文件。 我需要更改 .xml 文件並以相同的名稱保存在 diff 文件夾中。
有許多具有相同名稱的對象。 需要全部改變。
-<object>
<name>hat</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
這是我用 Python 編寫的代碼。 但它拋出錯誤。
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))
我認為ET.parse命令需要 for 循環中 XML 文件的完整路徑。 所以你可以試試這個:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.