0

I'm a noob programmer and am trying to open a bunch of .txt files containing data on each row so I can create XML tags for each row. For example, if the .txt file to open and tag looked like this:

John Smith
Harvard
4.00
1600

I need to use XML tags in Python to have it look like this:

<name> John Smith </name>
<university> Harvard </university>
<gpa> 4.00 </gpa>
<sat> 1600 </sat>

This seems like a fairly simple thing to do, though for some reason I can't locate a source on how to do so. I'm using Python 3.3, can someone help?

4

1 回答 1

1

这是您的示例的代码:

tags = ['name', 'university', 'gpa', 'sat']
xml = ''

with open('data.txt') as data:
    # Reading data and filtering out the whitespace
    lines = [line.strip() for line in data.readlines()]

    # Generating xml
    xml = '\n'.join(['<{0:s}> {1:s} </{0:s}>'.format(tag, value)
                 for tag, value in zip(tags, lines)])
于 2012-12-04T00:40:18.187 回答