merged_xml = ET.tostring(root, encoding='utf-8')
with open('merged_annotations.xml', 'wb') as output_file:
output_file.write(merged_xml)
完整的代码如下:
import zipfile
import xml.etree.ElementTree as ET
def merge_annotations(zip_file_path):
root = ET.Element('root')
with zipfile.ZipFile(zip_file_path, 'r') as zip_file:
for file_name in zip_file.namelist():
if file_name == 'annotations.xml':
xml_data = zip_file.read(file_name)
xml_root = ET.fromstring(xml_data)
for child in xml_root:
root.append(child)
merged_xml = ET.tostring(root, encoding='utf-8')
with open('merged_annotations.xml', 'wb') as output_file:
output_file.write(merged_xml)
import os
folder_path = '/path/to/zip/files'
for file_name in os.listdir(folder_path):
file_path = os.path.join(folder_path, file_name)
if file_name.endswith('.zip'):
merge_annotations(file_path)
merged_xml = ET.tostring(root, encoding='utf-8')
with open('merged_annotations.xml', 'wb') as output_file:
output_file.write(merged_xml)
完整的代码如下:
import xml.etree.ElementTree as ET
def merge_xml(xml_path_list):
root = ET.Element('root')
for xml_path in xml_path_list:
with open(xml_path, 'r') as xml_file:
xml_data = xml_file.read()
xml_root = ET.fromstring(xml_data)
for child in xml_root:
root.append(child)
merged_xml = ET.tostring(root, encoding='utf-8')
with open('merged_annotations.xml', 'wb') as output_file:
output_file.write(merged_xml)