Python text file to xml

眉间皱痕 提交于 2019-12-06 06:58:01

问题


I have one question about transforming a text file to XML. I have done nice conversion of text file and it's look like:

Program: 5 Start: 2013-09-11 05:30:00 Duration 06:15:00 Title: INFOCANALE

And my output in XML will be like

<data>
  <eg>
    <program>Program 5</program>
    <start>2013-09-11 05:30:00</start>
    <duration>06:15:00</duration>
    <title>INFOCANALE</title>
  </eg>
</dat‌​a>

Can python convert text file to XML?
Can you help me with some advice, or some code.


回答1:


I think easiest way would be to change your file into csv file like this:

Program,Start,Duration,Title
5,2013-09-11 05:30:00,06:15:00,INFOCANALE

And then convert it like:

from lxml import etree
import csv

root = etree.Element('data')

rdr = csv.reader(open("your file name here"))
header = rdr.next()
for row in rdr:
    eg = etree.SubElement(root, 'eg')
    for h, v in zip(header, row):
        etree.SubElement(eg, h).text = v

f = open(r"C:\temp\data2.xml", "w")
f.write(etree.tostring(root))
f.close()

# you also can use
# etree.ElementTree(root).write(open(r"C:\temp\data2.xml", "w"))


来源:https://stackoverflow.com/questions/18739501/python-text-file-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!