Python create XML from Csv within a loop

后端 未结 1 2010
甜味超标
甜味超标 2021-01-25 11:08

I am trying to create a xml file from a csv

CSV:

CatOne, CatTwo, CatThree
ProdOne, ProdTwo, ProdThree
ProductOne, ProductTwo, ProductThree
1条回答
  •  醉话见心
    2021-01-25 11:47

    Ok I found out how to solve it.

    I will answer my own question here, it might be help someone else I hope

    #! usr/bin/python
    # -*- coding: utf-8 -*-
    import csv, sys, os
    from lxml import etree
    
    def main():
        csvFile = 'test.csv'
        xmlFile = open('myData.xml', 'w')
        csvData = csv.reader(open(csvFile), delimiter='\t')
    
        header = csvData.next()
        counter = 0
        root = etree.Element('root')
    
        for row in csvData:
            prod = etree.SubElement(root,'prod')
            for index in range(0, len(header)):
                child = etree.SubElement(prod, header[index])
                child.text = row[index].decode('utf-8')
                prod.append(child
    
        result = etree.tostring(root, pretty_print=True)
        xmlFile.write(result)
    
    if __name__ == '__main__':
        main()
    

    0 讨论(0)
提交回复
热议问题