Python -- open xml file, change data based on data from csv, save as new xml file

Viewed 107

thanks for reading.

I'm very new to python, and even newer to xml files. I have a baseline xml file that I'm trying to update with data from a row in a csv.

4 pieces of data to change based on the 5 (find column4 and replace with column5) columns in the row of the csv. The csv will contain 30-50 rows, so I'm looking to generate 30-50 different xml files.

My csv file looks like this:

heading1,heading2,heading3,heading4,heading5
dataA1,dataA2,dataA3,dataA4,dataA5
dataB1,dataB2,dataB3,dataB4,dataB5
dataC1,dataC2,dataC3,dataC4,dataC5

XML data is like:

 <Scalar name="system">
  <Attribute name="sysDataA1" convert="ascii">dataA1</Attribute>
  <Attribute name="sysDataA2" convert="ascii">dataA2</Attribute>

<Scalar name="hm2NetStaticGroup">
 <Attribute name="hm2NetDataA3">dataA3</Attribute>

And then as I mentioned previously, the last changes would just be a simple find and replace of all occurrences of dataA4 with dataA5, and then save the new xml file with all the fields updated as "template-data1A.xml".

I have working code for the find and replace portion of the script, but I am struggling hard with how to pull the data from the csv rows and create unique xml files from the template.

This is the working code for the find and replace of dataA4, but again, not sure how to make the file save with dataA1 appended to the name of the file.

import xml.etree.ElementTree as ET

with open('template.xml', encoding='UTF-8') as t:
  tree = ET.parse(t)
  root = tree.getroot()

  for elem in root.iter():
    try:
      elem.text = elem.text.replace('301', '302')
    except AttributeError:
      pass

tree.write('template-dataA1.xml', encoding='UTF-8')

This is what I've been working with on the csv data:

# open csv file and print data from column.
import csv

var1 = "dataA1", "dataA2", "dataA3", "dataA4", "dataA5"

csv_dic = {var1: []}
csvFile = csv.reader(open('airData.csv', 'rt'))
for row in csvFile:
    csv_dic[var1].append(row[0])
for column in row:
    print(column)

I just tried to print the column to see what data it is getting, and it just keeps going to the last row in my csv and printing that. Doesn't matter if I change row[0] to row[1]. What am I misunderstanding here?

0 Answers
Related