Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8738797
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T10:48:19+00:00 2026-06-13T10:48:19+00:00

I am using Python to convert CSV files to XML format. The CSV files

  • 0

I am using Python to convert CSV files to XML format. The CSV files have a varying amount of rows ranging anywhere from 2 (including headers) to infinity. (realistically 10-15 but unless there’s some major performance issue, I’d like to cover my bases) In order to convert the files I have the following code:

for row in csvData:
    if rowNum == 0:
        xmlData.write('    <'+csvFile[:-4]+'-1>' + "\n")
        tags = row
        # replace spaces w/ underscores in tag names
        for i in range(len(tags)):
            tags[i] = tags[i].replace(' ', '_')
    if rowNum == 1: 
        for i in range(len(tags)):
            xmlData.write('        ' + '<' + tags[i] + '>' \
                          + row[i] + '</' + tags[i] + '>' + "\n")
        xmlData.write('    </'+csvFile[:-4]+'-1>' + "\n" + '    <' +csvFile[:-4]+'-2>' + "\n")
    if rowNum == 2:
        for i in range(len(tags)):
            xmlData.write('        ' + '<' + tags[i] + '>' \
                          + row[i] + '</' + tags[i] + '>' + "\n")
        xmlData.write('    </'+csvFile[:-4]+'-2>' + "\n")
    if rowNum == 3:
        for i in range(len(tags)):
            xmlData.write('<'+csvFile[:-4]+'-3>' + "\n" + '        ' + '<' + tags[i] + '>' \
                          + row[i] + '</' + tags[i] + '>' + "\n")
        xmlData.write('    </'+csvFile[:-4]+'-3>' + "\n")

    rowNum +=1
xmlData.write('</csv_data>' + "\n")
xmlData.close()

As you can see, I have the upper-level tags set to be created manually if the row exists. Is there a more efficient way to achieve my goal of creating the <csvFile-*></csvFile-*> tags rather than repeating my code 15+ times? Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T10:48:20+00:00Added an answer on June 13, 2026 at 10:48 am

    I would use xml.etree.ElementTree or lxml.etree to write the XML. xml.etree.ElementTree is in the standard library, but does not have built-in pretty-printing. (You could use the indent function from here, however).

    lxml.etree is a third-party module, but it has built-in pretty-printing in its tostring method.

    Using lxml.etree, you could do something like this:

    import lxml.etree as ET
    
    csvData = [['foo bar', 'baz quux'],['bing bang', 'bim bop', 'bip burp'],]
    csvFile = 'rowboat'
    name = csvFile[:-4]
    root = ET.Element('csv_data')
    for num, tags in enumerate(csvData):
        row = ET.SubElement(root, '{f}-{n}'.format(f = name, n = num))
        for text in tags:
            text = text.replace(' ', '_')
            tag = ET.SubElement(row, text)
            tag.text = text
    
    print(ET.tostring(root, pretty_print = True))
    

    yields

    <csv_data>
      <row-0>
        <foo_bar>foo_bar</foo_bar>
        <baz_quux>baz_quux</baz_quux>
      </row-0>
      <row-1>
        <bing_bang>bing_bang</bing_bang>
        <bim_bop>bim_bop</bim_bop>
        <bip_burp>bip_burp</bip_burp>
      </row-1>
    </csv_data>
    

    Some suggestions:

    • In Python, almost never do you need to say

      for i in range(len(tags)):
          # do stuff with tags[i]
      

      Instead say

      for tag in tags:
      

      to loop over all the items in tags.

    • Also instead of manually counting the times through a loop with

      num = 0
      for tags in csvData:
          num += 1
      

      instead use the enumerate function:

      for num, tags in enumerate(csvData):
      
    • Strings like

      '        ' + '<' + tags[i] + '>' \
                               + row[i] + '</' + tags[i] + '>' + "\n"
      

      are incredibly difficult to read. It mixes together logic of
      indentation, with the XML syntax of tags, with the minutia of end of
      line characters. That’s where xml.etree.ElementTree or lxml.etree
      will help you. It will take care of the serialization of the XML for
      you; all you need to provide is the relationship between the XML elements.
      The code will be much more readable and easier to maintain.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to convert xlsx file to xls format using python. The reason is
I have an XML file which I want to convert into JSON file using
using python i am generating a KML file from a csv file containing lat/long
I'm trying to convert the output of vmstat into a CSV file using Python,
How can I convert a .csv file into .dbf file using a python script?
I have a project using python and i want to convert the php to
I am using python's CSV module to iterate over the rows of a column.
How would I convert a file to a HEX string using Python? I have
can anybody tell me how to append xml files using python this is my
I'm trying to convert SVG to PNG using Python, Cairo and librsvg. Everything is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.