亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用python修改目錄中的多個.xml文件

使用python修改目錄中的多個.xml文件

偶然的你 2023-07-11 16:17:26
我正在嘗試修改文件夾中的多個 .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)


查看完整回答
反對 回復 2023-07-11
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號