pass_the_kavasier
pass_the_kavasier

Reputation: 107

How do I extract multiple values out of a single cell from csv to xml using python

I'm trying to convert a csv to xml for soap api purposes, but I need some to extract multiple values from a single field and populate each one of those values to its respective field in the xml file.

sample of my csv looks like:

81303~E8889~81300~7295~71942,AR,West High

My code looks something like this:

import csv

print('writing xml')

file_reader = csv.reader(open('test_csv_python.csv', 'r'), delimiter = ',')

xml_file = open('student_data.xml', 'w')

xml_file.write('<?xml version="1.0" encoding="UTF-8"?>' '\n')
xml_file.write('<sdistrict>' '\n')
for row in file_reader:
    xml_file.write('    ' + '<citycodes>' '\n')
    xml_file.write('    ' + '   ' + '<distnumber>' + row[0].split('~') + '</distnumber>' '\n')
    xml_file.write('    ' + '</citycodes>' '\n')
    xml_file.write('    ' + '<clientid>CUSTOM_VALUE</clientid>' '\n')
xml_file.write('</sdistrict>')

xml_file.close()

What I'm looking for is something like this:

<sdistricts>
             <citycodes>
                            <distnumber>129</distnumber>
                            <distnumber>118</distnumber>
                            <distnumber>576</distnumber>
                            <distnumber>498</distnumber>
                            <distnumber>332</distnumber>
             </citycodes>
</sdistricts>

How do I split the data in that particular row? I need to separate split on the tilde.

Using .split('~') gets me this error: TypeError: can only concatenate str (not "list") to str

Upvotes: 0

Views: 242

Answers (1)

Eric Truett
Eric Truett

Reputation: 3010

You need to add an inner loop to handle one or more results from the split operation. The error comes from trying to cocatenate a string (the XML tag) and a list (the result of split).

distnumbers = '\n'.join([f'<distnumber>{item}</distnumber>'
                                          for item in row[0].split('~')])

As an aside, this seems like an unpythonic and fragile way to build XML. I would build up a python data structure and then convert to XML in one pass, using a library such as XML (standard library), dicttoxml, or a custom function.

Upvotes: 0

Related Questions