07-06-2022, 02:01 PM
CSV to XML – How to Convert in Python?
<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"452015","slug":"default","valign":"top","reference":"auto","count":"1","readonly":"","score":"4","best":"5","gap":"5","greet":"Rate this post","legend":"4\/5 - (1 vote)","size":"24","width":"113.5","_legend":"{score}\/{best} - ({count} {votes})"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 113.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 4/5 – (1 vote) </div>
</div>
<h2>Problem Formulation</h2>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2022/07/csv_to_xml-1024x576.jpg" alt="python csv to xml" class="wp-image-452066" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/csv_to_xml-1024x576.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...to_xml.jpg 1280w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p><strong>Input</strong>: You have some data in a CSV file stored in <code>'my_file.csv'</code> where the first row is the header and the remaining rows are values associated to the column names in the header.</p>
<pre class="wp-block-preformatted"><code><strong>Name,Job,Age,Income</strong>
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000</code></pre>
<p><strong>Desired Output</strong>: You want to store the data in an XML file <code>'my_file.xml'</code> so that each row is represented by an XML <code><row></code> tag and each column value is associated with a specific column header tag. </p>
<pre class="wp-block-preformatted"><code><data> <row id='Alice'></code>
<code> <Name>Alice</Name></code>
<code> <Job>Programmer</Job></code>
<code> <Age>23</Age></code>
<code> <Income>110000</Income> </row>
<code> <row id='Bob'></code>
<code> <Name>Bob</Name></code>
<code> <Job>Executive</Job></code>
<code> <Age>34</Age></code>
<code> <Income>90000</Income> </row></code></code>
<code> <row id='Carl'></code>
<code> <Name>Carl</Name></code>
<code> <Job>Sales</Job></code>
<code> <Age>45</Age></code>
<code> <Income>50000</Income> </row>
</data></code></pre>
<h2>Python CSV to XML – Basic Example</h2>
<p>You can convert a CSV to an XML using the following approach:</p>
<ul>
<li>Read the whole CSV file into your Python script.</li>
<li>Store the first row as header data that is needed to name your custom XML tags (e.g., <code><Name></code>, <code><Job></code>, <code><Age></code>, and <code><Income></code> in our example). </li>
<li>Create a function <code>convert_row()</code> that converts each row separately to an XML representation of that row using <a rel="noreferrer noopener" href="https://blog.finxter.com/string-formatting-vs-format-vs-formatted-string-literal/" data-type="post" data-id="13190" target="_blank">basic string formatting</a>. </li>
<li>Iterate over the data row-wise using <code><a href="https://blog.finxter.com/how-to-read-a-csv-file-into-a-python-list/" data-type="post" data-id="8185" target="_blank" rel="noreferrer noopener">csv.reader()</a></code> and convert each CSV row to XML using your function <code>convert_row()</code>.</li>
</ul>
<p>Here’s the code for copy&paste:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""><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></pre>
<p>Yay! </p>
<p>Note that instead of printing to the shell, you could print it to a file if this is what you need. Here’s how:</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a href="https://blog.finxter.com/correct-way-to-write-line-to-file-in-python/" data-type="post" data-id="37630">How to <code>print()</code> to a file in Python?</a></p>
<h2>Pandas CSV to XML</h2>
<p>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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="1,11,12,15" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre>
<h2>Related CSV Conversion Tutorials</h2>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/convert-csv-to-json-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-json-in-python/" target="_blank">python convert csv to json</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/convert-csv-to-excel-xlsx-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-excel-xlsx-in-python/" target="_blank">python convert csv to excel (xlsx)</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/convert-csv-to-dictionary-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-dictionary-in-python/" target="_blank">python convert csv to dictionary</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-convert-csv-to-parquet/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-parquet/" target="_blank">python convert csv to parquet</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-list/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-list/" target="_blank" rel="noreferrer noopener">python convert csv to list</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-list-of-lists/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-list-of-lists/" target="_blank" rel="noreferrer noopener">python convert csv to list of lists</a></li>
<li><a href="https://blog.finxter.com/convert-csv-to-list-of-tuples-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-list-of-tuples-in-python/" target="_blank" rel="noreferrer noopener">python convert csv to list of tuples</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-text-file-csv-to-txt/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-text-file-csv-to-txt/" target="_blank" rel="noreferrer noopener">python convert csv to txt</a></li>
<li><a href="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" data-type="URL" data-id="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" target="_blank" rel="noreferrer noopener">python convert csv to dataframe</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-list-of-dictionaries/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-list-of-dictionaries/" target="_blank" rel="noreferrer noopener">python convert csv to list of dictionaries</a></li>
</ul>
</div>
https://www.sickgaming.net/blog/2022/07/...in-python/
<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"452015","slug":"default","valign":"top","reference":"auto","count":"1","readonly":"","score":"4","best":"5","gap":"5","greet":"Rate this post","legend":"4\/5 - (1 vote)","size":"24","width":"113.5","_legend":"{score}\/{best} - ({count} {votes})"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 113.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 4/5 – (1 vote) </div>
</div>
<h2>Problem Formulation</h2>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2022/07/csv_to_xml-1024x576.jpg" alt="python csv to xml" class="wp-image-452066" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/csv_to_xml-1024x576.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...to_xml.jpg 1280w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p><strong>Input</strong>: You have some data in a CSV file stored in <code>'my_file.csv'</code> where the first row is the header and the remaining rows are values associated to the column names in the header.</p>
<pre class="wp-block-preformatted"><code><strong>Name,Job,Age,Income</strong>
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000</code></pre>
<p><strong>Desired Output</strong>: You want to store the data in an XML file <code>'my_file.xml'</code> so that each row is represented by an XML <code><row></code> tag and each column value is associated with a specific column header tag. </p>
<pre class="wp-block-preformatted"><code><data> <row id='Alice'></code>
<code> <Name>Alice</Name></code>
<code> <Job>Programmer</Job></code>
<code> <Age>23</Age></code>
<code> <Income>110000</Income> </row>
<code> <row id='Bob'></code>
<code> <Name>Bob</Name></code>
<code> <Job>Executive</Job></code>
<code> <Age>34</Age></code>
<code> <Income>90000</Income> </row></code></code>
<code> <row id='Carl'></code>
<code> <Name>Carl</Name></code>
<code> <Job>Sales</Job></code>
<code> <Age>45</Age></code>
<code> <Income>50000</Income> </row>
</data></code></pre>
<h2>Python CSV to XML – Basic Example</h2>
<p>You can convert a CSV to an XML using the following approach:</p>
<ul>
<li>Read the whole CSV file into your Python script.</li>
<li>Store the first row as header data that is needed to name your custom XML tags (e.g., <code><Name></code>, <code><Job></code>, <code><Age></code>, and <code><Income></code> in our example). </li>
<li>Create a function <code>convert_row()</code> that converts each row separately to an XML representation of that row using <a rel="noreferrer noopener" href="https://blog.finxter.com/string-formatting-vs-format-vs-formatted-string-literal/" data-type="post" data-id="13190" target="_blank">basic string formatting</a>. </li>
<li>Iterate over the data row-wise using <code><a href="https://blog.finxter.com/how-to-read-a-csv-file-into-a-python-list/" data-type="post" data-id="8185" target="_blank" rel="noreferrer noopener">csv.reader()</a></code> and convert each CSV row to XML using your function <code>convert_row()</code>.</li>
</ul>
<p>Here’s the code for copy&paste:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""><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></pre>
<p>Yay! </p>
<p>Note that instead of printing to the shell, you could print it to a file if this is what you need. Here’s how:</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a href="https://blog.finxter.com/correct-way-to-write-line-to-file-in-python/" data-type="post" data-id="37630">How to <code>print()</code> to a file in Python?</a></p>
<h2>Pandas CSV to XML</h2>
<p>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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="1,11,12,15" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre>
<h2>Related CSV Conversion Tutorials</h2>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/convert-csv-to-json-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-json-in-python/" target="_blank">python convert csv to json</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/convert-csv-to-excel-xlsx-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-excel-xlsx-in-python/" target="_blank">python convert csv to excel (xlsx)</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/convert-csv-to-dictionary-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-dictionary-in-python/" target="_blank">python convert csv to dictionary</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-convert-csv-to-parquet/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-parquet/" target="_blank">python convert csv to parquet</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-list/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-list/" target="_blank" rel="noreferrer noopener">python convert csv to list</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-list-of-lists/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-list-of-lists/" target="_blank" rel="noreferrer noopener">python convert csv to list of lists</a></li>
<li><a href="https://blog.finxter.com/convert-csv-to-list-of-tuples-in-python/" data-type="URL" data-id="https://blog.finxter.com/convert-csv-to-list-of-tuples-in-python/" target="_blank" rel="noreferrer noopener">python convert csv to list of tuples</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-text-file-csv-to-txt/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-text-file-csv-to-txt/" target="_blank" rel="noreferrer noopener">python convert csv to txt</a></li>
<li><a href="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" data-type="URL" data-id="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" target="_blank" rel="noreferrer noopener">python convert csv to dataframe</a></li>
<li><a href="https://blog.finxter.com/python-convert-csv-to-list-of-dictionaries/" data-type="URL" data-id="https://blog.finxter.com/python-convert-csv-to-list-of-dictionaries/" target="_blank" rel="noreferrer noopener">python convert csv to list of dictionaries</a></li>
</ul>
</div>
https://www.sickgaming.net/blog/2022/07/...in-python/