XML到CSV格式

时间:2013-07-06 15:44:29

标签: python xml csv argparse

我有一个将csv转换为xml到csv的程序。但是,当我将其转换回csv时,格式化出错了。最初csv文件是这样的:

x1    y1    z1    x2    y2    z2    cost
 1     2     3     4     5     6       7

依此类推。此数据也使用excel表示。 然后我将其转换为xml,如下所示:

<Solution version="1.0">
  <DrillHoles total_holes="238">
    <description>
      <hole hole_id="1">
        <collar>1, 2, 3</collar>
        <toe>4, 5, 6</toe>
        <cost>7</cost>
      </hole>

*请注意,这只是整个事情的一部分,但对于这个例子来说已经足够了。 因此,当我将其转换回csv格式时,它似乎是这样的:

 x1    y1     z1    x2    y2    z2    cost
123                 456               7

其中x1y1z1x2y2z2cost在excel中的一列中混乱。这也用excel表示。

这是我生成xml的代码:

def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)        
    head = SubElement(root, 'DrillHoles')
    description = SubElement(head,'description')
    current_group = None
    i = 1
    for row in reader.next():
        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})

            collar = SubElement(current_group,'collar')
            toe = SubElement(current_group,'toe')
            cost1 = SubElement(current_group,'cost')
            collar.text = ', '.join((x1,y1,z1))
            toe.text = ', '.join((x2,y2,z2))
            cost1.text = cost
        i+=1
    head.set('total_holes', '%s'%i)
    indent.indent(root)
    tree.write(outfile)

生成csv:     def generate_csv(root,outfile):         打开(outfile,'w')作为文件_:

        writer = csv.writer(file_, delimiter="\t")
        writer.writerow(['x1'] + ['y1'] + ['z1'] + ['x2'] + ['y2'] + ['z2'] + ['cost'])
        for a in zip(root.findall("DrillHoles/description/hole/collar"),
                 root.findall("DrillHoles/description/hole/toe"),
                 root.findall("DrillHoles/description/hole/cost")):
            writer.writerow([x.text for x in a])

请帮助谢谢 编辑:我想我可能需要多个分隔符,但我不知道如何将其纳入此程序。

2 个答案:

答案 0 :(得分:1)

您似乎错过了分割,它与生成xml时的连接((x1,y1,z1))对称。像这样:

for a in zip(root.findall("DrillHoles/description/hole/collar"),
         root.findall("DrillHoles/description/hole/toe"),
         root.findall("DrillHoles/description/hole/cost")):
    collars, toes, cost = a
    collars = [x.strip() for x in collars.text.split(',')]
    toes = [x.strip() for x in toes.text.split(',')]
    cost = [cost.text]
    writer.writerow(collars + toes + cost)

答案 1 :(得分:0)

你可以尝试在csv编写器类中使用excel方言,因此excel会正确检测分隔符:

尝试更改行:

writer = csv.writer(file_,delimiter =“\ t”)

到这一行:

writer = csv.writer(file_,dialect ='excel')

但如果您需要制表符作为分隔符,则可以在excel中导入csv文件时尝试修剪设置