Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] CSV to XML – How to Convert in Python?

#1
CSV to XML – How to Convert in Python?

4/5 – (1 vote)

Problem Formulation


python csv to xml

Input: You have some data in a CSV file stored in 'my_file.csv' where the first row is the header and the remaining rows are values associated to the column names in the header.

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

Desired Output: You want to store the data in an XML file 'my_file.xml' so that each row is represented by an XML <row> tag and each column value is associated with a specific column header tag.

<data> <row id='Alice'>
<Name>Alice</Name>
<Job>Programmer</Job>
<Age>23</Age>
<Income>110000</Income> </row>
<row id='Bob'>
<Name>Bob</Name>
<Job>Executive</Job>
<Age>34</Age>
<Income>90000</Income> </row>

<row id='Carl'>
<Name>Carl</Name>
<Job>Sales</Job>
<Age>45</Age>
<Income>50000</Income> </row>
</data>

Python CSV to XML – Basic Example


You can convert a CSV to an XML using the following approach:

  • Read the whole CSV file into your Python script.
  • Store the first row as header data that is needed to name your custom XML tags (e.g., <Name>, <Job>, <Age>, and <Income> in our example).
  • Create a function convert_row() that converts each row separately to an XML representation of that row using basic string formatting.
  • Iterate over the data row-wise using csv.reader() and convert each CSV row to XML using your function convert_row().

Here’s the code for copy&paste:

# Convert CSV file to XML string
import csv filename = 'my_file.csv' def convert_row(headers, row): s = f'<row id="{row[0]}">\n' for header, item in zip(headers, row): s += f' <{header}>' + f'{item}' + f'</{header}>\n' return s + '</row>' with open(filename, 'r') as f: r = csv.reader(f) headers = next® xml = '<data>\n' for row in r: xml += convert_row(headers, row) + '\n' xml += '</data>' print(xml)

Output:

<data>
<row id="Alice"> <Name>Alice</Name> <Job>Programmer</Job> <Age>23</Age> <Income>110000</Income>
</row>
<row id="Bob"> <Name>Bob</Name> <Job>Executive</Job> <Age>34</Age> <Income>90000</Income>
</row>
<row id="Carl"> <Name>Carl</Name> <Job>Sales</Job> <Age>45</Age> <Income>50000</Income>
</row>
</data>

Yay!

Note that instead of printing to the shell, you could print it to a file if this is what you need. Here’s how:

? Learn More: How to print() to a file in Python?

Pandas CSV to XML


You can also use pandas instead of the csv module to read the CSV file into your Python script. Everything else remains similar—I highlighted the lines that have changed in the following code snippet:

import pandas as pd def convert_row(headers, row): s = f'<row id="{row[0]}">\n' for header, item in zip(headers, row): s += f' <{header}>' + f'{item}' + f'</{header}>\n' return s + '</row>' df = pd.read_csv("my_file.csv")
headers = df.columns.tolist()
xml = '<data>\n' for _, row in df.iterrows(): xml += convert_row(headers, row) + '\n' xml += '</data>'
print(xml)

Related CSV Conversion Tutorials




https://www.sickgaming.net/blog/2022/07/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Convert MIDI to MP3 in Python – A Quick Overview xSicKxBot 0 2,395 09-02-2023, 02:04 PM
Last Post: xSicKxBot
  [Tut] How to Convert an Octal Escape Sequence in Python – And Vice Versa? xSicKxBot 0 1,334 12-08-2022, 01:23 PM
Last Post: xSicKxBot
  [Tut] How to Convert Octal String to Integer in Python xSicKxBot 0 1,301 12-04-2022, 08:39 AM
Last Post: xSicKxBot
  [Tut] Python Convert Hex to Base64 xSicKxBot 0 1,278 11-30-2022, 09:32 PM
Last Post: xSicKxBot
  [Tut] How to Convert Bool (True/False) to a String in Python? xSicKxBot 0 1,305 10-04-2022, 11:37 AM
Last Post: xSicKxBot
  [Tut] Python Convert Image (JPG, PNG) to CSV xSicKxBot 0 1,297 09-10-2022, 12:05 PM
Last Post: xSicKxBot
  [Tut] Python Convert Parquet to CSV xSicKxBot 0 1,185 09-02-2022, 03:20 PM
Last Post: xSicKxBot
  [Tut] Python Convert Markdown Table to CSV xSicKxBot 0 1,223 09-01-2022, 01:21 AM
Last Post: xSicKxBot
  [Tut] How to Convert a Log to a CSV File in Python? xSicKxBot 0 1,291 08-30-2022, 02:11 AM
Last Post: xSicKxBot
  [Tut] Python – How to Convert KML to CSV? xSicKxBot 0 1,202 08-21-2022, 08:08 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016