gpt4 book ai didi

python - 如何将多个 XML 文件解析为多个 CSV 文件?

转载 作者:数据小太阳 更新时间:2023-10-29 02:38:20 25 4
gpt4 key购买 nike

我使用此代码解析了 XML 文件,该代码适用于单个 xml 输入到单个 csv 输出。我尝试使用 glob 处理多个输入以及多个 csv 输出,但我知道这是不正确的。

import glob
import xml.etree.ElementTree as et
import csv

for file in glob.glob('./*.xml'):
with open(file) as f:
tree = et.parse(f)
nodes = tree.getroot()

with open(f'{f[:-4]}edited.csv', 'w') as ff:
cols = ['dateTime','x','y','z','motion','isMoving','stepCount','groupAreaId','commit']
nodewriter = csv.writer(ff)
nodewriter.writerow(cols)
for node in nodes:
values = [ node.attrib.get(kk, '') for kk in cols]
nodewriter.writerow(values)

我应该如何更改以获得多个 csv 输出?

最佳答案

您的代码当前使用文件句柄来形成输出文件名。代替 f 使用 file 如下:

import glob
import xml.etree.ElementTree as et
import csv

for file in glob.glob('./*.xml'):
with open(file) as f:
tree = et.parse(f)
nodes = tree.getroot()

with open(f'{file[:-4]}edited.csv', 'w') as ff:
cols = ['dateTime','x','y','z','motion','isMoving','stepCount','groupAreaId','commit']
nodewriter = csv.writer(ff)
nodewriter.writerow(cols)
for node in nodes:
values = [ node.attrib.get(kk, '') for kk in cols]
nodewriter.writerow(values)

关于python - 如何将多个 XML 文件解析为多个 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56896188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com