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"

Converter script:

# 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

    # 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:


This script can be executed giving it as an argument to the Python interpreter:


Or by marking it as executable and executing it directly:

chmod +x

The output file will look like this:

  <Entry id="1">
    <First Name>Rachel</First Name>
    <Last Name>Booker</Last Name>
  <Entry id="2">
    <First Name>Laura</First Name>
    <Last Name>Grey</Last Name>
  <Entry id="3">
    <First Name>Craig</First Name>
    <Last Name>Johnson</Last Name>
  <Entry id="4">
    <First Name>Mary</First Name>
    <Last Name>Jenkins</Last Name>
  <Entry id="5">
    <First Name>Jamie</First Name>
    <Last Name>Smith</Last Name>