A possible solution is to first load the csv into Pandas and then convert it row by row into XML, as so:

import pandas as pd
df = pd.read_csv('untitled.txt', sep='|')

With the sample data (assuming separator and so on) loaded as:

          Title                   Type Format  Year Rating  Stars  \
0  Enemy Behind           War,Thriller    DVD  2003     PG     10   
1  Transformers  Anime,Science Fiction    DVD  1989      R      9   

             Description  
0          Talk about...  
1  A Schientific fiction  

And then converting to xml with a custom function:

def convert_row(row):
    return """<movietitle="%s">
    <type>%s</type>
    <format>%s</format>
    <year>%s</year>
    <rating>%s</rating>
    <stars>%s</stars>
    <description>%s</description>
</movie>""" % (
    row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, row.Description)

print '\n'.join(df.apply(convert_row, axis=1))

This way you get a string containing the xml:

<movietitle="Enemy Behind">
    <type>War,Thriller</type>
    <format>DVD</format>
    <year>2003</year>
    <rating>PG</rating>
    <stars>10</stars>
    <description>Talk about...</description>
</movie>
<movietitle="Transformers">
    <type>Anime,Science Fiction</type>
    <format>DVD</format>
    <year>1989</year>
    <rating>R</rating>
    <stars>9</stars>
    <description>A Schientific fiction</description>
</movie>

that you can dump in to a file or whatever.

Inspired by this great answer.


Edit: Using the loading method you posted (or a version that actually loads the data to a variable):

import csv              
f = open('movies2.csv')
csv_f = csv.reader(f)   
data = []

for row in csv_f: 
   data.append(row)
f.close()

print data[1:]

We get:

[['Enemy Behind', 'War', 'Thriller', 'DVD', '2003', 'PG', '10', 'Talk about...'], ['Transformers', 'Anime', 'Science Fiction', 'DVD', '1989', 'R', '9', 'A Schientific fiction']]

And we can convert to XML with minor modifications:

def convert_row(row):
    return """<movietitle="%s">
    <type>%s</type>
    <format>%s</format>
    <year>%s</year>
    <rating>%s</rating>
    <stars>%s</stars>
    <description>%s</description>
</movie>""" % (row[0], row[1], row[2], row[3], row[4], row[5], row[6])

print '\n'.join([convert_row(row) for row in data[1:]])

Getting identical results:

<movietitle="Enemy Behind">
    <type>War</type>
    <format>Thriller</format>
    <year>DVD</year>
    <rating>2003</rating>
    <stars>PG</stars>
    <description>10</description>
</movie>
<movietitle="Transformers">
    <type>Anime</type>
    <format>Science Fiction</format>
    <year>DVD</year>
    <rating>1989</rating>
    <stars>R</stars>
    <description>9</description>
</movie>
Answer from robertoia on Stack Overflow
Top answer
1 of 5
23

A possible solution is to first load the csv into Pandas and then convert it row by row into XML, as so:

import pandas as pd
df = pd.read_csv('untitled.txt', sep='|')

With the sample data (assuming separator and so on) loaded as:

          Title                   Type Format  Year Rating  Stars  \
0  Enemy Behind           War,Thriller    DVD  2003     PG     10   
1  Transformers  Anime,Science Fiction    DVD  1989      R      9   

             Description  
0          Talk about...  
1  A Schientific fiction  

And then converting to xml with a custom function:

def convert_row(row):
    return """<movietitle="%s">
    <type>%s</type>
    <format>%s</format>
    <year>%s</year>
    <rating>%s</rating>
    <stars>%s</stars>
    <description>%s</description>
</movie>""" % (
    row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, row.Description)

print '\n'.join(df.apply(convert_row, axis=1))

This way you get a string containing the xml:

<movietitle="Enemy Behind">
    <type>War,Thriller</type>
    <format>DVD</format>
    <year>2003</year>
    <rating>PG</rating>
    <stars>10</stars>
    <description>Talk about...</description>
</movie>
<movietitle="Transformers">
    <type>Anime,Science Fiction</type>
    <format>DVD</format>
    <year>1989</year>
    <rating>R</rating>
    <stars>9</stars>
    <description>A Schientific fiction</description>
</movie>

that you can dump in to a file or whatever.

Inspired by this great answer.


Edit: Using the loading method you posted (or a version that actually loads the data to a variable):

import csv              
f = open('movies2.csv')
csv_f = csv.reader(f)   
data = []

for row in csv_f: 
   data.append(row)
f.close()

print data[1:]

We get:

[['Enemy Behind', 'War', 'Thriller', 'DVD', '2003', 'PG', '10', 'Talk about...'], ['Transformers', 'Anime', 'Science Fiction', 'DVD', '1989', 'R', '9', 'A Schientific fiction']]

And we can convert to XML with minor modifications:

def convert_row(row):
    return """<movietitle="%s">
    <type>%s</type>
    <format>%s</format>
    <year>%s</year>
    <rating>%s</rating>
    <stars>%s</stars>
    <description>%s</description>
</movie>""" % (row[0], row[1], row[2], row[3], row[4], row[5], row[6])

print '\n'.join([convert_row(row) for row in data[1:]])

Getting identical results:

<movietitle="Enemy Behind">
    <type>War</type>
    <format>Thriller</format>
    <year>DVD</year>
    <rating>2003</rating>
    <stars>PG</stars>
    <description>10</description>
</movie>
<movietitle="Transformers">
    <type>Anime</type>
    <format>Science Fiction</format>
    <year>DVD</year>
    <rating>1989</rating>
    <stars>R</stars>
    <description>9</description>
</movie>
2 of 5
3

I tried to generalize robertoia's function convert_row for any header instead of writing it by hand.

import csv  
import pandas as pd
            
f = open('movies2.csv')
csv_f = csv.reader(f)   
data = []

for row in csv_f: 
   data.append(row)
f.close()

df = pd.read_csv('movies2.csv')
header= list(df.columns)

def convert_row(row):
     str_row = """<%s>%s</%s> \n"""*(len(header)-1)
     str_row = """<%s>%s""" +"\n"+ str_row + """</%s>"""
     var_values = [list_of_elments[k] for k in range(1,len(header)) for list_of_elments in [header,row,header]]
     var_values = [header[0],row[0]]+var_values+[header[0]]
     var_values =tuple(var_values)
     return str_row % var_values

text ="""<collection shelf="New Arrivals">"""+"\n"+'\n'.join([convert_row(row) for row in data[1:]])+"\n" +"</collection >"
print(text)
with open('output.xml', 'w') as myfile: 
  myfile.write(text)

Of course with pandas now, it is simpler to just use to_xml() :

df= pd.read_csv('movies2.csv')
with open('outputf.xml', 'w') as myfile: 
  myfile.write(df.to_xml())

🌐
Aspose
products.aspose.com › aspose.cells › python via java › conversion › csv to xml
Python CSV to XML - CSV to XML Converter | products.aspose.com
November 13, 2025 - Add a library reference (import the library) to your Python project. Load CSV file with an instance of Workbook. Convert CSV to XML by calling Workbook.save method.
Discussions

Converting CSV file to XML
Excel can export data in an XML format. Open it in Excel and simply export it, no programming needed. I believe you do need to enable developer mode. More on reddit.com
🌐 r/CodingHelp
6
1
September 8, 2024
Read xml column inside csv file with Python
Hi, I am very new in Python and need to read an xml column inside a csv file with Python. I can see some code on google on how to read that csv file but I don’t know how to read the xml column inside the csv file. Can someone help? any idea would be appreciated. Thank you! More on discuss.python.org
🌐 discuss.python.org
0
0
July 22, 2022
How do I convert XML into a CSV in the most efficient way possible?
How To Parse and Convert XML to CSV using Python . More on reddit.com
🌐 r/datascience
7
3
July 5, 2017
Excel or CSV file to XML - ADF
Hi, I want to convert excel/csv file into XML format. This xml is used as a body text for a rest api. Basically i need to send excel data to a REST API using ADF. Rest API accepts xml format. excel file is present in storage container. What are the possible ways to achieve this? Python script ... More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
February 25, 2024
🌐
GitHub
github.com › SilentJMA › Tradebyte-CSV-To-XML-with-Python
GitHub - SilentJMA/Tradebyte-CSV-To-XML-with-Python: Converting a Tradebyte Panda file from CSV to XML by using Python. · GitHub
Key elements to modify include field names, XML tags, and data mapping. Run the Python script using the following command: ... The script will read the source CSV file, transform the data, and generate an XML file named PandaDDMMYYYYHHMMSS.xml DD:Day, MM: Month, YYYY: Year, HH: Hour, MM: Minute, SS: Secondin the same directory.
Author   SilentJMA
🌐
AskPython
askpython.com › home › converting data in csv to xml in python
Converting Data in CSV to XML in Python - AskPython
April 4, 2023 - It would be highly necessary to read the CSV file as a dataframe. The check on the input file as CSV and the output file as XML is done using Python String’s endswith() function. The file always ends with its extension, in the case of CSV is ‘.csv’, and in the case of XML is ‘.xml’. The endswith() function checks the last characters of the string with the given input.
🌐
e-iceblue
e-iceblue.com › Tutorials › Python › Spire.XLS-for-Python › Program-Guide › Conversion › convert-csv-to-xml-in-python.html
Convert CSV to XML in Python (Handle Real-World Cases)
In this guide, we’ll explore how to convert CSV files into XML using Spire.XLS for Python. You’ll learn how to convert CSV into both Excel XML format (SpreadsheetML) and standard XML for general use.
🌐
GitHub
gist.github.com › justinvw › 927047
Simple script to convert a CSV file to XML · GitHub
Simple script to convert a CSV file to XML · Raw · csv2xml.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Zamzar
developers.zamzar.com › python › csv-to-xml
Convert CSV files to XML using a powerful Python API | Zamzar
from zamzar import ZamzarClient # Signup for a Zamzar API Account or retrieve your existing API Key from https://developers.zamzar.com zamzar = ZamzarClient("YOUR_API_KEY_GOES_HERE") # Converts /tmp/example.csv to /tmp/example.xml zamzar.convert("/tmp/example.csv", "xml").store("/tmp/").delete_all_files()
Find elsewhere
🌐
ActiveState
code.activestate.com › recipes › 577423-convert-csv-to-xml
Convert CSV to XML « Python recipes « ActiveState Code
October 11, 2010 - # example CSV file: myData.csv # id,code name,value # 36,abc,7.6 # 40,def,3.6 # 9,ghi,6.3 # 76,def,99 import sys import os import csv if len(sys.argv) != 2: os._exit(1) path=sys.argv[1] # get folder as a command line argument os.chdir(path) csvFiles = [f for f in os.listdir('.') if f.endswith('.csv') or f.endswith('.CSV')] for csvFile in csvFiles: xmlFile = csvFile[:-4] + '.xml' csvData = csv.reader(open(csvFile)) xmlData = open(xmlFile, 'w') xmlData.write('<?xml version="1.0"?>' + "\n") # there must be only one top-level tag xmlData.write('<csv_data>' + "\n") rowNum = 0 for row in csvData: if
🌐
Reddit
reddit.com › r/codinghelp › converting csv file to xml
r/CodingHelp on Reddit: Converting CSV file to XML
September 8, 2024 -

I don't know if this is the right place to post this, but I'm looking for someone who can create a process to convert a daily csv file to xml that can be imported into our billing software.

I'm just looking for a way to find someone to pay to get this set up for me (the company I work for). I've tried searching and have come up empty, so am reaching out to reddit where I get all of my questions answered!

To sum up, I'm looking for where I would search to find someone to write a program / process for me to use to convert a csv file into xml to be able to be imported into a billing software program.

Thanks!

🌐
Sonra
sonra.io › home › xml › xml conversion using python in 2025
XML Conversion Using Python in 2026 - Sonra
January 14, 2025 - Output consists of multiple csv files where each csv file contains each tag and its corresponding details. ... xmltodict is a Python library that makes working with XML feel like working with JSON by converting XML into Python dictionaries.
🌐
Blogger
beyondvalence.blogspot.com › 2014 › 04 › python-converting-csv-to-xml-and-json.html
Valence Analytics: Python: Converting CSV to XML and JSON
April 22, 2014 - To read the CSV file, we use the csv.reader() method, and set the delimiter to a comma. Then we create the XML file to which we will write the output, and write the XML heading and the root element.
🌐
Finxter
blog.finxter.com › 5-best-ways-to-convert-csv-to-xml-in-python
5 Best Ways to Convert CSV to XML in Python – Be on the Right Side of Change
March 1, 2024 - The csv2xml library is a specialized Python package that can convert CSV to XML with a single line of code.
🌐
Automate the Boring Stuff
automatetheboringstuff.com › 3e › chapter18.html
Chapter 18 - CSV, JSON, and XML Files, Automate the Boring Stuff with Python, 3rd Ed
Copy specific data from a CSV file to an Excel file, or vice versa. Check for invalid data or formatting mistakes in CSV files and alert the user about these errors. Read data from a CSV file as input for your Python programs. While CSV files are useful for storing rows of data that have the exact same columns, the JSON and XML formats can store a variety of data structures.
🌐
Quora
quora.com › How-can-CSV-data-be-converted-into-XML-and-or-JSON-using-Python
How can CSV data be converted into XML and/or JSON using Python? - Quora
Answer: Probably with first an input routine to open and start reading the CSV file line by line until end of file. Then collect all data into a Python defined data structure. (The format of a JSON string tells you what data structure to use to create a nested output structure.) Then you use a ...
🌐
Teleport
goteleport.com › resources › tools › csv-to-xml-converter
CSV to XML Converter | Instantly Transform CSV to XML | Teleport
Convert CSV data to XML instantly with our free online tool. Simplify your data conversions with fast, accurate processing.
🌐
Python.org
discuss.python.org › python help
Read xml column inside csv file with Python - Python Help - Discussions on Python.org
July 22, 2022 - Hi, I am very new in Python and need to read an xml column inside a csv file with Python. I can see some code on google on how to read that csv file but I don’t know how to read the xml column inside the csv file. Can …
🌐
Datasciencehorizons
datasciencehorizons.com › advanced-file-handling-in-python-working-with-csv-json-and-xml
Advanced File Handling in Python: Working with CSV, JSON, and XML – Data Science Horizons
May 17, 2024 - JSON: Be mindful of the structure and avoid deeply nested objects when possible. Use schemas to validate JSON data. XML: Manage namespaces and avoid excessive depth in element hierarchy. Use libraries that support schema validation. This article has covered the essentials of handling CSV, JSON, and XML files using Python.
🌐
Ubuntu
help.ubuntu.com › community › Converting CSV to XML
Converting CSV to XML - Community Help Wiki
April 8, 2011 - In order to run it, you must save the previous as 'csv2xml.py' and change the permissions to executable. Or you can also invoke it explicitly: ... Another script for Python3 allows you to set a lot of input and output formatting options directly with command-line options. PHP is a widely-used general-purpose scripting language that fits particularly well with XML...
🌐
Reddit
reddit.com › r/datascience › how do i convert xml into a csv in the most efficient way possible?
r/datascience on Reddit: How do I convert XML into a CSV in the most efficient way possible?
July 5, 2017 -

Currently, I'm receiving a large amount of data from different devices, an issue I'm having is that the data is in different formats. Ideally, I would like them to be CSV but I need to do this without a heavy overhead.

So far I've been looking into parse generators and I've seen data pipelining come up a few times.

Help a geek out

🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1588592 › excel-or-csv-file-to-xml-adf
Excel or CSV file to XML - ADF - Microsoft Q&A
February 25, 2024 - I understand that you want to convert excel/csv to XML using ADF. You can use Azure Function to write python code convert the Excel/CSV file to XML format and run the azure function from ADF pipeline.