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

2024-06-17 09:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图修改文件夹中的多个.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)

    # adds additional subchild items annotation and image
    source = myroot.find('source')
    annotate = ET.SubElement(source, 'annotation') 
    annotate.tail = '\n\t\t'
    annotate.text = 'custom'

    source = myroot.find('source')
    img = ET.SubElement(source, 'image')
    img.tail = '\n\t'
    img.text = 'custom'
    
    #remove <path> element
    path = myroot.getchildren()[2]
    myroot.remove(path)
    
    mytree.write(dir, '*.xml')

Tags: 文件pathsourcesizeannotationxmlfolderfilename
1条回答
网友
1楼 · 发布于 2024-06-17 09:18:53

不能使用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)

相关问题 更多 >