简体   繁体   English

如何使用Python将大型xml文件转换为csv

[英]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. 我想将非常大的XML文件转换为CSV格式,而不用硬编码标记名。

Can anyone help me out? 谁能帮我吗?

Firstly, you need to parse your XML files. 首先,您需要解析XML文件。 This can be done via ElementTree API : 这可以通过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. 还有一些将XML直接解析为字典的解决方案。

Then csv.DictWriter can be used to save the dictionary as CSV. 然后,可以使用csv.DictWriter将字典另存为CSV。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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