从CSV文件生成XML文件

时间:2013-05-31 14:14:06

标签: python csv

所以我有这个代码生成以下xml文件:

  <?xml version="1.0"?>
  -<Solution version="1.0">-<DrillHoles total_holes="238">
         -<description>
               -<hole hole_id="1">
                    <hole toe="5797.82" cost="102.12" collar="5720.443070.942642.19"/>

但是

collar ="5720.443070.942642.19",它应该是

collar = "5720.44, 3070.94, 2642.19"

是在csv文件中编写的。我只是不知道如何在点之间加一个逗号。请帮忙

以下是代码:

    import csv
    from xml.etree.ElementTree import Element, SubElement, Comment, tostring
    from xml.etree.ElementTree import ElementTree
    import xml.etree.ElementTree as etree

    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)

    head = SubElement(root, 'DrillHoles')
    head.set('total_holes', '238')

    description = SubElement(head,'description')


    with open ('1250_12.csv', 'r') as data:
         current_group = None
         reader = csv.reader(data)
         i = 0
         for row in reader:
             if i > 0:
                x1,y1,z1,x2,y2,z2,cost = row
                if current_group is None or i != current_group.text:
                     current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                     information = SubElement (current_group, 'hole',{'collar':x1 + y1 + z1,
                                                              'toe':x2 + y2 + z2,
                                                              'cost':cost})
             i+=1

   tree.write(open('holes.xml','w'))

2 个答案:

答案 0 :(得分:3)

而不是:

{'collar':x1 + y1 + z1,
 'toe':x2 + y2 + z2,
 'cost':cost}

使用:

{'collar': ', '.join([x1, y1, z1]),
 'toe':    ', '.join([x2, y2, z2]),
 'cost':   cost}

或者:

{'collar': '%s, %s, %s' % (x1, y1, z1),
 'toe':    '%s, %s, %s' % (x2, y2, z2),
 'cost':   cost}

答案 1 :(得分:1)

而不是

'collar':x1 + y1 + z1,

'collar': ", "join((x1, y1, z1))