Convert CSV to XML with Python
Run this on your own computer using Python 3. Save a UTF-8, comma-delimited input.csv in the same folder as the script. The first record must contain unique, nonempty headers; quoted commas and line breaks are parsed as fields.
Before you start
- Python 3 installed. Package commands below use a local virtual environment on macOS/Linux; on Windows use .venv\Scripts\python.exe in place of .venv/bin/python.
- Keep the original CSV. These examples read the complete table into memory and create separate output files.
- Save the Python code as convert_csv.py beside input.csv.
- Install the listed package when required, then run the script. Check the generated output before using it elsewhere.
import csv
from pathlib import Path
with open("input.csv", encoding="utf-8-sig", newline="") as source:
reader = csv.reader(source, strict=True)
headers = next(reader)
rows = list(reader)
if not headers or any(not h for h in headers) or len(set(headers)) != len(headers):
raise ValueError("Use unique, nonempty column headers")
if any(len(row) != len(headers) for row in rows):
raise ValueError("Every record must have the same number of fields as the header")
import xml.etree.ElementTree as ET
root = ET.Element("records")
for row in rows:
record = ET.SubElement(root, "record")
for header, value in zip(headers, row):
ET.SubElement(record, "field", name=header).text = value
ET.indent(root)
ET.ElementTree(root).write("output.xml", encoding="utf-8", xml_declaration=True)python3 convert_csv.pyLimits and output
- Writes records/record/field elements with the CSV header in each field name attribute. This differs from using column names as XML element names and safely accommodates spaces in headers. XML escapes text and attribute values; unsupported XML characters still need validation.
Documentation: Python CSV reader and writer; Python ElementTree XML output