{"id":126224,"date":"2022-07-03T09:44:31","date_gmt":"2022-07-03T09:44:31","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=452015"},"modified":"2022-07-03T09:44:31","modified_gmt":"2022-07-03T09:44:31","slug":"csv-to-xml-how-to-convert-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/07\/03\/csv-to-xml-how-to-convert-in-python\/","title":{"rendered":"CSV to XML \u2013 How to Convert in Python?"},"content":{"rendered":"<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;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 113.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\"> 4\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2>Problem Formulation<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2022\/07\/csv_to_xml-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/07\/csv_to_xml-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/07\/csv_to_xml.jpg 1280w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<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>\n<pre class=\"wp-block-preformatted\"><code><strong>Name,Job,Age,Income<\/strong>\nAlice,Programmer,23,110000\nBob,Executive,34,90000\nCarl,Sales,45,50000<\/code><\/pre>\n<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>\n<pre class=\"wp-block-preformatted\"><code>&lt;data> &lt;row id='Alice'><\/code>\n<code> &lt;Name>Alice&lt;\/Name><\/code>\n<code> &lt;Job>Programmer&lt;\/Job><\/code>\n<code> &lt;Age>23&lt;\/Age><\/code>\n<code> &lt;Income>110000&lt;\/Income> &lt;\/row>\n<code> &lt;row id='Bob'><\/code>\n<code> &lt;Name>Bob&lt;\/Name><\/code>\n<code> &lt;Job>Executive&lt;\/Job><\/code>\n<code> &lt;Age>34&lt;\/Age><\/code>\n<code> &lt;Income>90000&lt;\/Income> &lt;\/row><\/code><\/code>\n<code> &lt;row id='Carl'><\/code>\n<code> &lt;Name>Carl&lt;\/Name><\/code>\n<code> &lt;Job>Sales&lt;\/Job><\/code>\n<code> &lt;Age>45&lt;\/Age><\/code>\n<code> &lt;Income>50000&lt;\/Income> &lt;\/row>\n&lt;\/data><\/code><\/pre>\n<h2>Python CSV to XML &#8211; Basic Example<\/h2>\n<p>You can convert a CSV to an XML using the following approach:<\/p>\n<ul>\n<li>Read the whole CSV file into your Python script.<\/li>\n<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>\n<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>\n<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>\n<\/ul>\n<p>Here&#8217;s the code for copy&amp;paste:<\/p>\n<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\nimport 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(r) xml = '&lt;data>\\n' for row in r: xml += convert_row(headers, row) + '\\n' xml += '&lt;\/data>' print(xml)<\/pre>\n<p>Output:<\/p>\n<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>\n&lt;row id=\"Alice\"> &lt;Name>Alice&lt;\/Name> &lt;Job>Programmer&lt;\/Job> &lt;Age>23&lt;\/Age> &lt;Income>110000&lt;\/Income>\n&lt;\/row>\n&lt;row id=\"Bob\"> &lt;Name>Bob&lt;\/Name> &lt;Job>Executive&lt;\/Job> &lt;Age>34&lt;\/Age> &lt;Income>90000&lt;\/Income>\n&lt;\/row>\n&lt;row id=\"Carl\"> &lt;Name>Carl&lt;\/Name> &lt;Job>Sales&lt;\/Job> &lt;Age>45&lt;\/Age> &lt;Income>50000&lt;\/Income>\n&lt;\/row>\n&lt;\/data><\/pre>\n<p>Yay! <\/p>\n<p>Note that instead of printing to the shell, you could print it to a file if this is what you need. Here&#8217;s how:<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" 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>\n<h2>Pandas CSV to XML<\/h2>\n<p>You can also use pandas instead of the csv module to read the CSV file into your Python script. Everything else remains similar&#8212;I highlighted the lines that have changed in the following code snippet:<\/p>\n<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\")\nheaders = df.columns.tolist()\nxml = '&lt;data>\\n' for _, row in df.iterrows(): xml += convert_row(headers, row) + '\\n' xml += '&lt;\/data>'\nprint(xml)<\/pre>\n<h2>Related CSV Conversion Tutorials<\/h2>\n<ul>\n<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>\n<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>\n<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>\n<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>\n<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>\n<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>\n<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>\n<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>\n<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>\n<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>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>4\/5 &#8211; (1 vote) Problem Formulation Input: You have some data in a CSV file stored in &#8216;my_file.csv&#8217; 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 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-126224","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/126224","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=126224"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/126224\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=126224"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=126224"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=126224"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}