gpt4 book ai didi

python - 循环并写入 CSV 文件?

转载 作者:行者123 更新时间:2023-12-01 09:32:55 27 4
gpt4 key购买 nike

我正在尝试循环遍历 XML 文件,并解析出我需要的元素。我可以很好地打印到控制台窗口,但结果太大,并且在结束之前填满整个控制台。因此,我尝试将所有内容转储到 CSV 文件中。现在,当脚本完成时,我似乎在 CSV 中每行只得到一个字符。我的代码肯定很接近,但显然有些问题。

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('C:\\path\\Recon.xml')
root = tree.getroot()

with open('C:\\path\\data.csv', 'w') as f:

for neighbor in root.iter('inputColumn'):
print(neighbor.attrib)
writer = csv.writer(f)
writer.writerows(neighbor.attrib)

我使用的是3.6.3!

只是在这里发布我的代码的最终版本......

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('C:\\path\\Recon.xml')
root = tree.getroot()

with open('C:\\path\\data.csv', 'w') as f:
writer = csv.writer(f)
for neighbor in root.iter('inputColumn'):
print(neighbor.attrib)
writer.writerow(neighbor.attrib)

这就是如此、如此、如此简单。在使用 Python 几年并且(基本上)讨厌它之后,我现在真的开始喜欢它了!

最佳答案

回答反射(reflect)上面的评论,以便将来引用。

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('C:\\path\\Recon.xml')
root = tree.getroot()

with open('C:\\path\\data.csv', 'w') as f:

writer = csv.writer(f)

for neighbor in root.iter('inputColumn'):
print(neighbor.attrib)
writer.writerow(neighbor.attrib)

关于python - 循环并写入 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49800525/

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