天天看點

檢查xml檔案中是否存在某個節點(python)

對于voc格式的資料集而言,删除某個節點後可能檔案中就 沒有主要根節點了,是以需要檢測,并删除那個廢掉的xml檔案。

代碼如下:

import xml.etree.cElementTree as ET
import os

path_root = ['/Applications/小仙女/tiquxml/shaixuanhou']  #xml儲存的路徑

for anno_path in path_root:
    xml_list = os.listdir(anno_path)
    for axml in xml_list:
        path_xml = os.path.join(anno_path, axml)
        print(path_xml)
        tree = ET.parse(path_xml)
        root = tree.getroot()
        i=0
        print("123")
        for child in root.findall('object'):
            if child!='':
                i=i+1
        if i==0:
          os.remove(path_xml)
        else:
            tree.write(os.path.join('/Applications/小仙女/tiquxml/wanzheng/', axml)) #儲存路徑