In the following example, the Python code will create a dictionary with the headers (fields on the first line) from the CSV input file and recreate the same structure in the XML output file.
Input file:
"Username","Identifier","First Name","Last Name" "booker12","9012","Rachel","Booker" "grey07","2070","Laura","Grey" "johnson81","4081","Craig","Johnson" "jenkins46","9346","Mary","Jenkins" "smith79","5079","Jamie","Smith"
Converter script:
#!/bin/python # Converter: CSV to XML import csv import xml.etree.ElementTree as xml input = 'input.csv' output = 'output.xml' # opening the CSV input file = open(input) reader = csv.reader(file, delimiter=',', quotechar='"') headers = next(reader) # creating the dictionary indexes = {} for header in headers: indexes[header] = headers.index(header) # creating the XML structure root = xml.Element("Collection") id = 0 for item in reader: id = id + 1 # creating each entry (element) entry = xml.Element("Entry") # setting an attribute to the entry entry.set('id',str(id)) root.append(entry) # adding each property to the entry for variable in indexes: entry_property = xml.SubElement(entry, variable) entry_property.text = item[indexes[variable]] # writing the XML structure to a file tree = xml.ElementTree(root) with open(output, "wb") as output_file: tree.write(output_file) exit()
This script can be executed giving it as an argument to the Python interpreter:
python converter.py
Or by marking it as executable and executing it directly:
chmod +x converter.py ./converter.py
The output file will look like this:
<Collection> <Entry id="1"> <Username>booker12</Username> <First Name>Rachel</First Name> <Identifier>9012</Identifier> <Last Name>Booker</Last Name> </Entry> <Entry id="2"> <Username>grey07</Username> <First Name>Laura</First Name> <Identifier>2070</Identifier> <Last Name>Grey</Last Name> </Entry> <Entry id="3"> <Username>johnson81</Username> <First Name>Craig</First Name> <Identifier>4081</Identifier> <Last Name>Johnson</Last Name> </Entry> <Entry id="4"> <Username>jenkins46</Username> <First Name>Mary</First Name> <Identifier>9346</Identifier> <Last Name>Jenkins</Last Name> </Entry> <Entry id="5"> <Username>smith79</Username> <First Name>Jamie</First Name> <Identifier>5079</Identifier> <Last Name>Smith</Last Name> </Entry> </Collection>