使用python修改目录中的多个.xml文件

我正在尝试修改文件夹中的多个 .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 ET

import xml.dom.minidom

import os


dir = '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)



偶然的你
浏览 93回答 1
1回答

陪伴而非守候

您不能ElementTree在一次调用中打开多个文件。只需循环它们:# your other imports...import globdir = 'Desktop/python_testing/xml/'for xml_file in glob.glob(dir + '/*.xml'):&nbsp; &nbsp; mytree = ET.parse(xml_file)&nbsp; &nbsp; # make your changes here...&nbsp; &nbsp; mytree.write(xml_file)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python