我正在尝试修改文件夹中的多个 .xml 文件并用其原始文件名覆盖这些文件。我可以成功修改一个文件,但是当我尝试添加代码来遍历多个文件时,没有任何变化。不确定我做错了什么。有人可以帮忙吗?谢谢。另外,Python 初学者。这是我正在更改的 XML 文件:<annotation> <folder>Images</folder> <filename>1.jpg</filename> <path>/Users/AAA/Desktop/data/imgs</path> <source> <database>Unknown</database> </source> <size> <width>1021</width> <height>1500</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>backpack</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>6</xmin> <ymin>1</ymin> <xmax>1021</xmax> <ymax>1466</ymax> </bndbox> </object></annotation>它应该是这样的:<annotation> <folder>backpack</folder> <filename>1.jpg</filename> <source> <database>backpack</database> <annotation>custom</annotation> <image>custom</image> </source> <size> <width>1021</width> <height>1500</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>backpack</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>6</xmin> <ymin>1</ymin> <xmax>1021</xmax> <ymax>1466</ymax> </bndbox> </object></annotation>这是我尝试修改文件夹中的多个文件的 python 代码:import xml.etree.ElementTree as ETimport xml.dom.minidomimport osdir = 'Desktop/python_testing/xml/'if os.path.isfile(dir): mytree = ET.parse(dir, '*.xml') myroot = mytree.getroot() # changes description of the elements for description in myroot.iter('folder'): new_desc = 'backpack' description.text = str(new_desc) for database in myroot.iter('database'): new_desc = 'backpack' database.tail = '\n\t\t' database.text = str(new_desc)
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
您不能ElementTree在一次调用中打开多个文件。只需循环它们:
# your other imports...
import glob
dir = 'Desktop/python_testing/xml/'
for xml_file in glob.glob(dir + '/*.xml'):
mytree = ET.parse(xml_file)
# make your changes here...
mytree.write(xml_file)
添加回答
举报
0/150
提交
取消