CSV文件,需要提取数据,格式化数据并转换为xml

时间:2013-09-10 09:45:09

标签: python xml csv extract formatting

这可能是一个非常简单的问题,但我只是回到了python的世界。 我有一个.csv文件,例如

FRAME, SEQID, CYCLE SEC, CYCLE COUNT, SIZE, GAMMA, GAIN0, GAIN1, GAIN2, GAIN3, GAIN4, GAIN5, SHUTTER0, SHUTTER1, SHUTTER2, SHUTTER3, SHUTTER4, SHUTTER5, LAT, LON, ALT, UTC
000000, 3371, 058, 0000, 3951616, 0.000, 64,64,64,64,64,64, 34,34,34,34,34,34, 52.53922000, 0.79127400, 48.300, 11:06:35.00
000001, 3372, 060, 0000, 3954176, 0.000, 64,64,64,64,64,64, 34,34,34,34,34,34, 52.53922033, 0.79127483, 48.400, 11:06:37.00
000002, 3373, 062, 0000, 3955200, 0.000, 64,64,64,64,64,64, 34,34,34,34,34,34, 52.53922050, 0.79127600, 48.400, 11:06:39.00

我需要提取'FRAME,LAT,LON'和&然后在.xml文件中将其格式化为这样。

<?xml version="1.0" encoding="utf-8"?>
<viewpointlist>
   <viewpoint>
      <vpid>VP000001</vpid>
      <lat>52.5254</lat>
      <lng>0.70886</lng>
   </viewpoint>
   <viewpoint>
      <vpid>VP000002</vpid>
      <lat>52.5254</lat>
      <lng>0.70886</lng>
   </viewpoint>

正如我所说,可能是一个简单的,它已经很长时间了。 预先感谢。 保罗

1 个答案:

答案 0 :(得分:0)

您可以使用csv模块来读取csv文件,使用ElementTree来创建xml:

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


root = Element('viewpointlist')
with open('test.csv') as f:
    reader = csv.DictReader(f)
    for line in reader:
        child = SubElement(root, "viewpoint")

        element = SubElement(child, 'vpid')
        element.text = line['FRAME']
        element = SubElement(child, 'lat')
        element.text = line[' LAT']
        element = SubElement(child, 'lng')
        element.text = line[' LON']

print tostring(root)

打印(为了便于阅读而缩进):

<viewpointlist>
    <viewpoint>
        <vpid>000000</vpid>
        <lat>52.53922000</lat>
        <lng>0.79127400</lng>
    </viewpoint>
    <viewpoint>
        <vpid>000001</vpid>
        <lat>52.53922033</lat>
        <lng>0.79127483</lng>
    </viewpoint>
    <viewpoint>
        <vpid>000002</vpid>
        <lat>52.53922050</lat>
        <lng>0.79127600</lng>
    </viewpoint>
</viewpointlist>