基于CSV中的行生成XML文件

时间:2016-07-25 17:27:17

标签: python xml python-2.7 csv elementtree

我有一张CSV,希望根据CSV中的每一行生成 XML文件。 现在它创建了一个XML文件,但只有 CSV中的最后一行。如何修改此脚本以生成EACH行的XML文件。理想情况下,基于列的文件名:"文件/实体名称" 。请参阅下面我目前所拥有的内容,谢谢!

# CSV module
import csv
# Stuff from the XML module
from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
import xml.etree.ElementTree as etree


# Topmost XML element
root = Element('root')
number = Element('number')
# Open a file
with open(r'U:\PROJECTS\Technical Graphics\book1.csv') as f:

    for row in csv.DictReader(f):
        root = Element('gmd:MD_Metadata')
        tree = ElementTree(root)
        for k, v in row.items():
            child = SubElement(root, k)
            child.text = v
            reader = csv.DictReader(f)

    tree.write(open(r'U:\PROJECTS\Technical Graphics\test.xml','w'))
    print tostring(root)

2 个答案:

答案 0 :(得分:0)

您可以在此处设置Root的值:

for row in csv.DictReader(f):
    root = Element('gmd:MD_Metadata')
    tree = ElementTree(root)
    filename = row.items()[7]  # where 7 is the column your interested in
    for k, v in row.items():
        child = SubElement(root, k)
        child.text = v
        reader = csv.DictReader(f)
        tree.write(open(r'U:\PROJECTS\Technical Graphics\' + filename  + '.xml','w'))
        print tostring(root)

答案 1 :(得分:0)

您只想创建一次csv.DictReader()类,而不是循环的每次迭代。

同样,您只需要创建一次root XML元素。

最后,从row.items()返回的项目的顺序是任意的,并不反映文件中字段的顺序。

试试这个:

# CSV module
import csv
# Stuff from the XML module
from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
import xml.etree.ElementTree as etree


# Topmost XML element
root = Element('root')
number = Element('number')
# Open a file
with open(r'U:\PROJECTS\Technical Graphics\book1.csv') as f:

    root = Element('gmd:MD_Metadata')
    tree = ElementTree(root)
    reader = csv.DictReader(f)
    for row in reader:
        xml_row = SubElement(root, "row")
        for k in reader.fieldnames:
            child = SubElement(xml_row, k)
            child.text = row[k]

    tree.write(open(r'U:\PROJECTS\Technical Graphics\test.xml','w'))
    print tostring(root)