prasanna777
prasanna777

Reputation: 11

How to convert large xml file into csv using Python

I want to convert a very large XML file into CSV format without hardcoding tagnames.

Can anyone help me out?

Upvotes: 0

Views: 3401

Answers (1)

Johann Hagerer
Johann Hagerer

Reputation: 1087

Firstly, you need to parse your XML files. This can be done via ElementTree API:

Example code:

import xml.etree.ElementTree as ET
root = ET.parse('your_data.xml').getroot()
with open("output.csv", "w") as file:
    for child in root:
        print(child.tag, child.attrib)
        # naive example how you could save to csv line wise
        file.write(child.tag+";"+child.attrib)

There are also solutions to parse your XMLs directly as dictionary.

Then csv.DictWriter can be used to save the dictionary as CSV.

Upvotes: 2

Related Questions