import os
import xml.etree.ElementTree as ET
from shutil import copy

class Tools:
    def __init__(self, xmls1, xmls2):
        self.xmls1 = xmls1
        self.xmls2 = xmls2
        
    def read_from_xml(self):
        xml1_dict = {}
        xml2_dict = {}
        for root, dir_list, file_list in os.walk(self.xmls1):
            for index, file_fn in enumerate(file_list):
                xml_fn = os.path.join(root, file_fn)
                xml1_dict[file_fn] = xml_fn

        for root, dir_list, file_list in os.walk(self.xmls2):
            for index, file_fn in enumerate(file_list):
                xml_fn = os.path.join(root, file_fn)
                xml2_dict[file_fn] = xml_fn
                
        for key, value in xml2_dict.items():
            if key in xml1_dict:
                tree1 = ET.parse(value)
                tree2 = ET.parse(xml1_dict[key])
                
                root1 = tree1.getroot()
                root2 = tree2.getroot()
                
                for object in root2.findall('object'):
                    root1.append(object)
                tree1.write('xml/{}'.format(key))
            else:
                copy(value, 'xml')
                
        for key, value in xml1_dict.items():
            if key not in xml2_dict:
                copy(value, 'xml')
                

if __name__ == '__main__':
    tool = Tools('xml1', 'xml2')
    tool.read_from_xml()

更多推荐