我正在尝试遍历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几年后,(基本上)讨厌它,我现在真的开始喜欢它!
答案 0 :(得分:1)
回答上述评论,以方便日后参考。
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)