#Python# 提取数据 写入txt

问题遇到的现象和发生背景

需求

img

img

img

我想要达到的结果

提取xml文件中的相关数据;写入到txt文件中;与相应图片对应;

dirname = r'D:\test'
 
import re
import os
import json
 
con = os.walk(dirname)
 
with open(dirname + "\\Label.txt", 'w+', encoding = 'utf-8') as f1:
    for _, __, FileList in con:
        for i in FileList:
            res = os.path.splitext(i)
            if res[1] == '.xml':
                d = {}
                lt = []
                with open(dirname + "\\" + i, 'r', encoding = 'utf-8') as f:
                    ls = re.findall(r'[XYs]="(.*?)"', f.read(), re.DOTALL)
                    lst = list(map(int, ls[:-1]))
                    lt.append(lst[:2])
                    lt.append(lst[2:4])
                    lt.append(lst[4:6])
                    lt.append(lst[6:8])
                    d['transcription'] = ls[-1]
                    d['points'] = lt[::]
                    d['difficult'] = False
                ss = json.dumps(d)
                f1.write(res[0] + '.jpg\t' + str([ss]) + "\n")