기계는 거짓말하지 않는다

Python XML ElementTree Read 본문

Python

Python XML ElementTree Read

KillinTime 2021. 10. 15. 21:43

XML ElementTree를 이용한 XML 파일 읽기

 

tempXML.xml

import os
import glob
import xml.etree.ElementTree as ET	# import module

# 모든 XML 파일 경로를 가져옴
ano_path = sorted(glob.glob(os.path.join("./", "*.xml")))

# XML 파일 하나씩 읽음
for annotation_path in ano_path:
    # XML 파일 읽기
    doc = ET.parse(annotation_path)
    # 최상위 XML 태그
    root = doc.getroot()

    # text 파일 이름
    filename = annotation_path.split("\\")[-1].split(".")[0] + ".txt"
    # text 저장 경로
    path = "./out/"
    
    with open(path + filename, "w") as f:
        # size 태그 찾기
        # 같은 이름의 태그가 많다면 findall
        size = root.find("size")
        
        # text 가져오기
        width = int(size.findtext("width"))
        height = int(size.findtext("height"))

        name = root.findtext("name")

        for object in root.iter("object"):
            xmin = float(object.find("bndbox").findtext("xmin"))
            ymin = float(object.find("bndbox").findtext("ymin"))
            xmax = float(object.find("bndbox").findtext("xmax"))
            ymax = float(object.find("bndbox").findtext("ymax"))

            f.write(f"{name} {xmin} {ymin} {xmax} {ymax} {width} {height}\n")

tempXML.txt

'Python' 카테고리의 다른 글

Python Thread  (0) 2022.04.23
Python 객체 유형, 자료형 확인  (0) 2021.12.06
Python Priority Queue  (0) 2021.10.13
Python DataFrame 데이터 분리 후 csv 생성  (0) 2021.10.08
Python GUI PyQt5, QtDesigner  (0) 2021.10.07
Comments