我正在尝试将xml解析为csv报告,但出现错误。我在PyCharm中的代码中“ DictWriter”没有变成蓝色。另外,如果我想添加列标题,该在哪里列出这些标题?预先感谢您提供的任何帮助。
import csv
import xml.etree.ElementTree as et
from collections import OrderedDict
doc = et.parse('response.xml')
csv_data = []
fields = ['SubjectKey', 'Action']
for elem in doc.findall('.//AuditRecord'):
inner_dict = OrderedDict({k: None for k in fields}) # PRE-POPULATES TEMP DICT
inner_dict['SubjectKey'] = elem.attrib['SubjectKey']
for item in elem.findall('.//*'):
if item.tag in fields:
if item.tag == 'AuditRecord':
inner_dict['AuditRecord_Action'] = item.attrib['Action']
else:
inner_dict[item.tag] = item.text
csv_data.append(inner_dict)
with open('Output.csv', 'w', newline='') as f:
w = csv.DictWriter(f, csv_data[0].keys())
w.writeheader()
w.writerows(csv_data)
这是我遇到的错误,然后出现空白的.csv:
w = csv.DictWriter(f, csv_data[0].keys())
IndexError: list index out of range