ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python]Python으로 .xml 파일 내용 수정하기
    기타 정보 2020. 4. 30. 20:04

     

     

    폴더 안에 있는 모든 xml파일 내용을 일괄적으로 수정할 필요가 생겨 코드를 작성하게 되었다

     

     

    1. 필요한 라이브러리 import

    import os
    import xml.etree.ElementTree as ET

    xml.etree.ElementTree는 xml 파싱을 위한 라이브러리 중 하나이다.

    os는 폴더나 파일에 접근하기 위해 필요하다.

     

     

    2. 폴더안에 있는 모든 xml 파일 이름 가져오기

    targetDir = r"C:\Users\lab_research\data\images\train"
    
    ##targetDir에서 .xml파일 이름들 리스트로 가져오기
    file_list = os.listdir(targetDir)
    xml_list = []
    for file in file_list:
        if '.xml' in file:
            xml_list.append(file)

    targetDir: 수정할 파일이 있는 폴더의 path 저장 ("앞에 있는 r은 python UnicodeError때문에 넣은 것)

    file_list: targetDir의 모든 파일 이름이 저장됨

    xml_list: xml파일의 이름을 저장할 리스트

     

    for문을 이용해 file_list의 파일 이름을 하나하나씩 접근

    파일이름에 '.xml'이 포함되어 있으면 xml_list에 추가

     

     

    3. xml 내용 가져와서 수정하기

    ##모든 .xml파일에 대해 수정
    for xml_file in xml_list:
        target_path = targetDir + "\\" + xml_file
        targetXML = open(target_path, 'rt', encoding='UTF8')
    
        tree = ET.parse(targetXML)
    
        root = tree.getroot()
    
        ##수정할 부분
        target_tag = root.find("path")
    
        original = target_tag.text     #원본 String
        modified = original.replace(r"/home/ailsb",r"C:\Users\lab_research")
        modified = modified.replace("/", "\\")
        target_tag.text = modified  #수정
          
        tree.write(target_path)

    xml_list의 모든 xml파일에 반복

    target_path: xml파일의 절대 경로

    root: xml의 최상위 루트 태그 

    현재 xml 내용이 이러한데 root는 최상위 태그인 annotation을 가리킨다. 

     

    target_tag: root.find를 이용해 수정하고자하는 태그를 찾는다. (나는 path 내용을 수정해야했다.)

    original: target_tag.text를 이용해 태그의 원본 내용을 가져온다.  

    modified: 나는 문자열의 특정 부분을 다른 문자열로 대체해야했기 때문에 replace함수를 썼다. 

                 replace가 아닌 일반적인 수정을 하는 경우 target_tag.text = "새로운내용" 이렇게 수정하면 된다.

    태그 내용을 수정할 문자열로 저장한 뒤 tree.write 해주면 xml이 수정된다. 

     

     

    python 전체 코드

    import os
    import xml.etree.ElementTree as ET
    
    targetDir = r"C:\Users\lab_research\data\images\train"
    num = 1
    
    ##targetDir에서 .xml파일 이름들 리스트로 가져오기
    file_list = os.listdir(targetDir)
    xml_list = []
    for file in file_list:
        if '.xml' in file:
            xml_list.append(file)
    
    ##모든 .xml파일에 대해 수정
    for xml_file in xml_list:
        target_path = targetDir + "\\" + xml_file
        targetXML = open(target_path, 'rt', encoding='UTF8')
    
        tree = ET.parse(targetXML)
    
        root = tree.getroot()
    
        ##수정할 부분
        target_tag = root.find("path")
    
        original = target_tag.text     #원본 String
        modified = original.replace(r"/home/ailsb/",r"C:\Users\kimsk\lab_research")
        modified = modified.replace("/", "\\")
        target_tag.text = modified  #수정
        print("[" + str(num) + "]" + xml_file + "[success]")
        
        tree.write(target_path)
        num += 1
    
    print("finished")
    

    댓글

Designed by Tistory.