【发布时间】:2019-06-21 17:46:52
【问题描述】:
我正在尝试解析下面代码中包含的“XML”文件,但对所有定义的变量都报错:
NameError: 名称“computer_name”未定义
这是“XML”文件的摘录(因为它不是真正的 xml 文件,所以我试图将变量设置为找到的行下方的行):
<p1:field>
<p1:name>NewComputerName</p1:name>
<p1:value>Computer01</p1:value>
</p1:field>
<p1:field>
<p1:name>NewComputerAssetTag</p1:name>
<p1:value>12345</p1:value>
</p1:field>
<p1:field>
<p1:name>AcquisitionDate</p1:name>
<p1:value>4/20/69</p1:value>
</p1:field>
这是我的代码:
import csv
import os
with open('csvtest.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(('Computer Name', 'Acquisition Date', 'Asset Tag'))
for filename in os.listdir('\\\\windb\\f$\\Technology\\V1\\0'):
if filename.endswith(".xml"):
with open(os.path.join('\\\\windb\\f$\\Technology\\V1\\0',filename), "r") as input:
for line in input:
if line.startswith(' <p1:name>NewComputerName</p1:name>'):
computer_name=next(input, '').strip()
computer_name=computer_name.split("<p1:value>")[1].split("</")[0]
elif line.startswith(' <p1:name>AcquisitionDate'):
acqDate=next(input, '').strip()
acqDate=acqDate.split("<p1:value>")[1].split("</")[0]
elif line.startswith(' <p1:name>NewComputerAssetTag'):
assTag=next(input, '').strip()
assTag=assTag.split("<p1:value>")[1].split("</")[0]
myData = [computer_name,acqDate,assTag]
writer.writerow(myData)
我希望这会将 3 个变量写入 CSV 文件,为目录中的每个 XML 文件附加一行。
输出为 NameError: name 'computer_name' is not defined
【问题讨论】:
标签: python xml-parsing python-import export-to-csv elementtree