简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM