Python在循环中从Csv创建XML

时间:2013-11-19 05:36:43

标签: python xml csv lxml

我正在尝试从csv

创建一个xml文件

CSV:

CatOne, CatTwo, CatThree
ProdOne, ProdTwo, ProdThree
ProductOne, ProductTwo, ProductThree

所需的XML:

<root>
  <prod>
    <CatOne>ProdOne</CatOne>
    <CatTwo>ProdTwo</CatTwo>
    <CatThree>ProdThree</CatThree>
  </prod>
  <prod>
    <CatOne>ProductOne</CatOne>
    <CatTwo>ProductTwo</CatTwo>
    <CatThree>ProductThree</CatThree>
  </prod>
</root>

这是我的代码:

#! 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()
    details = csvData.next()
    details2 = csvData.next()
    root = etree.Element('root')

    prod = etree.SubElement(root,'prod')
    for index in range(0, len(header)):
        child = etree.SubElement(prod, header[index])
        child.text = details[index]
        prod.append(child)   
    prod = etree.SubElement(root,'prod')
    for index in range(0, len(header)):
        child = etree.SubElement(prod, header[index])
        child.text = details2[index]
        prod.append(child)      
    result = etree.tostring(root, pretty_print=True)
    xmlFile.write(result)  

if __name__ == '__main__':
    main()

我得到了所需的输出,但我这样做的方式真的很糟糕。 我希望以一种通用的方式拥有它,我相信它可能更加pythonic 但我无法弄清楚如何做到这一点。 如果csv有10行甚至20行,代码也应该有效。

感谢您的帮助

1 个答案:

答案 0 :(得分:5)

好的,我发现了如何解决它。

我将在这里回答我自己的问题,这可能对我希望的其他人有所帮助

#! 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()