![]() |
|
[Tut] CSV to XML – How to Convert in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] CSV to XML – How to Convert in Python? (/thread-99670.html) |
[Tut] CSV to XML – How to Convert in Python? - xSicKxBot - 07-06-2022 CSV to XML – How to Convert in Python? 4/5 – (1 vote) Problem Formulation ![]() Input: You have some data in a CSV file stored in Code: 'my_file.csv'Code: Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000Desired Output: You want to store the data in an XML file Code: 'my_file.xml'Code: <row>Code: <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>You can convert a CSV to an XML using the following approach:
Here’s the code for copy&paste: Code: # 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(r) xml = '<data>\n' for row in r: xml += convert_row(headers, row) + '\n' xml += '</data>' print(xml)Output: Code: <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 Code: print()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: Code: 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)
|