'Create two different xml files from single csv file using python

I am pretty new to python and I have one csv file and based on one condition I need to create two different xml files. The condition based on which I need to create two xml is as follows:

If Primary spindle == 1 then data related to it will go to xml1 else xml2.

This is how my xml looks like as shown in image: enter image description here

The code I am writing is as follows:

import csv
file = open(r'C:\Users\hu170f\MultiSpindleArchitechture\New folder\MAAP-S12_LH_UP_PASS-LN1-V1.csv')
csvreader = csv.reader(file)
xmlFile = r'C:\Users\hu170f\Documents\TEST\myData4.xml' 
xmlFile1 = r'C:\Users\hu170f\Documents\TEST\myData5.xml'  
#header = next(csvreader)

xmlData = open(xmlFile, 'w')
xmlData.write('<?xml version="1.0"   encoding = "UTF-8"?>' + "\n")
# there must be only one top-level tag
xmlData.write('<MCD>' + "\n")

xmlData1 = open(xmlFile1, 'w')
xmlData1.write('<?xml version="1.0"   encoding = "UTF-8"?>' + "\n")
# there must be only one top-level tag
xmlData1.write('<MCD>' + "\n")


#print(header)
rows = []
for row in csvreader:
    rows.append(row)
#print(len(rows))
#print(len(row))
Field = " "
Value = " "
counter = 0

for i in rows:
    tag = i
    #print(tag)
    #print(len(rows))
    for j in range(len(tag)):
        tag[j] = tag[j].replace(' ', '_')
        if j == 0:
            #print("Field = ", tag[j])
            Field = tag[j]
            counter = counter +1
        else:
            #print("Value = ", tag[j])
            Value = tag[j]
    
    if(counter%2 == 0):    
        xmlData.write('    ' + '<' + Field + '>' \
                          + Value + '</' + Field  + '>' + "\n") 
    else :
        xmlData1.write('    ' + '<' + Field + '>' \
                          + Value + '</' + Field  + '>' + "\n")
    
    
    
        
        
xmlData.write('</MCD>' + "\n")
xmlData.close() 

xmlData1.write('</MCD>' + "\n")
xmlData1.close() 
#print(rows[6])
        
file.close()

I want both xml to contain common data from Header to LN and then data from WorkStep UUID till secondary Spindle based on the condition in each xml file.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source