【问题标题】:How to convert mutiple XML files into csv using python?如何使用 python 将多个 XML 文件转换为 csv?
【发布时间】:2018-05-28 09:58:25
【问题描述】:
<?xml version="1.0" encoding="UTF-8"?><document>
    <Task>"Test"</Task>
    <author Test="xxx" lang="EN" type="Twitter"/>
    <comments>Text Text Text Text.
</comments>
</document>

以上是我的示例 XML。需要将此 XML 转换并写入 CSV

【问题讨论】:

    标签: python xml pandas


    【解决方案1】:

    使用 ElementTree

    演示:

    from xml.etree import ElementTree as ET
    import os
    import csv
    
    res = []
    
    for filename in os.listdir(path):     #Check Dir For file
        if filename.endswith('.xml'):     #Check if extension is '.xml'
            filePath = os.path.join(path, filename)
            x = ET.parse(filePath)        #Read xml using 'ET.parse'
            res.append([x.find("Task").text.strip(), x.find("author").attrib["type"], x.find("comments").text.strip()])    #Get required values. 
    
    with open(r"C:\Users\zk0h098\Desktop\testFiles\A.csv", "w") as infile:
        writer = csv.writer(infile, delimiter=",")
        writer.writerow(["Task", "Author", "Comments"])    #Write Header
        for line in res:
            writer.writerow(line)                     #Write content
    

    【讨论】:

    • 感谢您的回答。如何在 ["FileName","Task", "Author", "Comments"] 之外的一列中获取 XML 文件名。
    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 2021-05-08
    • 2021-11-21
    • 2021-07-31
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多