python3读取xml文件并打印
xml文件格式如下图:
运行print_xml.py
from fileinput import filename
import os
import sys
import xml.etree.ElementTree as ET
import glob
#--------读取xml文件数据并打印--------#
# 该xml读取方式匹配:https://blog.youkuaiyun.com/weixin_46438576/article/details/123729428?spm=1001.2014.3001.5502
# 第一步:将.xml文件放置在'xml_dir'目录下
# 第二步:运行print_xml.py
#----------------------------------#
def print_xml(xml_dir):
# 获取该xml目录下所有文件xml名称并print打印
os.chdir(xml_dir)
annotations = os.listdir('.')
annotations = glob.glob(str(annotations)+'*.xml')
print(annotations)
print('\n')
# 遍历该xml目录下所有xml文件数据并打印
for i, file in enumerate(annotations):
print("xml_file:", file)
in_file = open(file)
tree = ET.parse(in_file)
root = tree.getroot()
# filename = root.find('annotation')
# print("filename:", filename)
for obj in root.iter('class'):
class_type = obj.text
Lwing_x = obj.find('Lwing_x').text
Lwing_y = obj.find('Lwing_y').text
Rwing_x = obj.find('Rwing_x').text
Rwing_y = obj.find('Rwing_y').text
print(class_type +' '+ Lwing_x+' '+ Lwing_y+' '+ Rwing_x+' '+ Rwing_y)
print('\n')
xml_dir='/home/guo/txt_2_xml/xml' #xml目录
print_xml(xml_dir)