003_xml中出現浮點數變為整數
阿新 • • 發佈:2021-01-28
# *_* coding : UTF-8 *_* import os import xml.etree.ElementTree as ET path = r'D:\03_date_work\ann' # 包含xml的資料夾路徑 def edit_xml(xml_file): """ 修改xml檔案 :param xml_file:xml檔案的路徑 :return: """ all_xml_file = os.path.join(path, xml_file) tree = ET.parse(all_xml_file) print(all_xml_file) objs = tree.findall('object') for ix, obj in enumerate(objs): obj_bnd = obj.find('bndbox') obj_xmin = obj_bnd.find('xmin') obj_ymin = obj_bnd.find('ymin') obj_xmax = obj_bnd.find('xmax') obj_ymax = obj_bnd.find('ymax') xmin = float(obj_xmin.text) ymin = float(obj_ymin.text) xmax = float(obj_xmax.text) ymax = float(obj_ymax.text) obj_xmin.text = str(round(xmin)) # 四捨五入轉為整數 obj_ymin.text = str(round(ymin)) obj_xmax.text = str(round(xmax)) obj_ymax.text = str(round(ymax)) tree.write(all_xml_file, method='xml', encoding='utf-8') # 覆蓋更新xml檔案 if __name__ == '__main__': files = os.listdir(path) # 獲取檔名列表 for i, file in enumerate(files): if file.endswith('.xml'): edit_xml(file)