问题
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>
</data>
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