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?

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;452015&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;4&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;4\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;113.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<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>&lt;row></code> tag and each column value is associated with a specific column header tag. </p>
<pre class="wp-block-preformatted"><code>&lt;data> &lt;row id='Alice'></code>
<code> &lt;Name>Alice&lt;/Name></code>
<code> &lt;Job>Programmer&lt;/Job></code>
<code> &lt;Age>23&lt;/Age></code>
<code> &lt;Income>110000&lt;/Income> &lt;/row>
<code> &lt;row id='Bob'></code>
<code> &lt;Name>Bob&lt;/Name></code>
<code> &lt;Job>Executive&lt;/Job></code>
<code> &lt;Age>34&lt;/Age></code>
<code> &lt;Income>90000&lt;/Income> &lt;/row></code></code>
<code> &lt;row id='Carl'></code>
<code> &lt;Name>Carl&lt;/Name></code>
<code> &lt;Job>Sales&lt;/Job></code>
<code> &lt;Age>45&lt;/Age></code>
<code> &lt;Income>50000&lt;/Income> &lt;/row>
&lt;/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>&lt;Name></code>, <code>&lt;Job></code>, <code>&lt;Age></code>, and <code>&lt;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&amp;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'&lt;row id="{row[0]}">\n' for header, item in zip(headers, row): s += f' &lt;{header}>' + f'{item}' + f'&lt;/{header}>\n' return s + '&lt;/row>' with open(filename, 'r') as f: r = csv.reader(f) headers = next® xml = '&lt;data>\n' for row in r: xml += convert_row(headers, row) + '\n' xml += '&lt;/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="">&lt;data>
&lt;row id="Alice"> &lt;Name>Alice&lt;/Name> &lt;Job>Programmer&lt;/Job> &lt;Age>23&lt;/Age> &lt;Income>110000&lt;/Income>
&lt;/row>
&lt;row id="Bob"> &lt;Name>Bob&lt;/Name> &lt;Job>Executive&lt;/Job> &lt;Age>34&lt;/Age> &lt;Income>90000&lt;/Income>
&lt;/row>
&lt;row id="Carl"> &lt;Name>Carl&lt;/Name> &lt;Job>Sales&lt;/Job> &lt;Age>45&lt;/Age> &lt;Income>50000&lt;/Income>
&lt;/row>
&lt;/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'&lt;row id="{row[0]}">\n' for header, item in zip(headers, row): s += f' &lt;{header}>' + f'{item}' + f'&lt;/{header}>\n' return s + '&lt;/row>' df = pd.read_csv("my_file.csv")
headers = df.columns.tolist()
xml = '&lt;data>\n' for _, row in df.iterrows(): xml += convert_row(headers, row) + '\n' xml += '&lt;/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/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016