Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python将多个XML文件转换为csv? “测试” 文本文本。_Python_Xml_Pandas - Fatal编程技术网

如何使用python将多个XML文件转换为csv? “测试” 文本文本。

如何使用python将多个XML文件转换为csv? “测试” 文本文本。,python,xml,pandas,Python,Xml,Pandas,上面是我的示例XML。需要使用ElementTree将此XML转换为CSV 演示: <?xml version="1.0" encoding="UTF-8"?><document> <Task>"Test"</Task> <author Test="xxx" lang="EN" type="Twitter"/> <comments>Text Text Text Text. </comments&

上面是我的示例XML。需要使用ElementTree将此XML转换为CSV

演示:

<?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文件名。
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