I am attempting to parse the "XML" file included in the code below but am getting error for all variables defined:
NameError: name 'computer_name' is not defined
Here is an excerpt from the "XML" file(because it is not a true xml file I am trying to set the variable to the line below the found line):
<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>
and here is my code:
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)
I expect this to write the 3 variables to the CSV file appending a row for each XML file in the directory.
The output is NameError: name 'computer_name' is not defined