该脚本实现快速、批量转换
import os
import xml.etree.ElementTree as ET
# 定义XML文件夹和TXT文件夹的路径
xml_folder = '/path/to/xml/files'
txt_folder = '/path/to/txt/files'
# 检查TXT文件夹是否存在,如果不存在则创建
if not os.path.exists(txt_folder):
os.makedirs(txt_folder)
# 遍历XML文件夹中的每个文件
for xml_file in os.listdir(xml_folder):
if xml_file.endswith('.xml'):
xml_path = os.path.join(xml_folder, xml_file)
tree = ET.parse(xml_path)
root = tree.getroot()
# 将XML文件内容写入对应的TXT文件中
txt_file = os.path.splitext(xml_file)[0] + '.txt'
txt_path = os.path.join(txt_folder, txt_file)
with open(txt_path, 'w') as txt:
for elem in root.iter():
if elem.text:
txt.write(elem.text + '\n')
print("XML转换为TXT完成!")