繁体   English   中英

解析所有 XML 文件并将它们转换为一个 CSV 文件

[英]Parse all the XML files and convert them to one CSV file

我正在尝试编写一个代码,在其中搜索目录中的所有 XML 文件,然后解析这些 XML 并将一些数据保存到 CSV 文件中。 我在那个目录中有 50 多个 XML 文件。 每当我运行我的代码时,都会创建一个 CSV 文件,但它只打印最后一个 xml 文件的数据。 如何将所有 XML 文件的数据打印到 CSV 文件?请帮忙这是我的代码:

from xml.dom.minidom import parse
import csv
import os

def writeToCSV(frelation):
    csvfile = open('data.csv', 'w')
    fieldnames = ['sub', 'sup']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    relation = frelation.getElementsByTagName("predicate")
    for elem in relation:
        sub = elem.attributes['sub'].value
        for elem1 in elem.getElementsByTagName("sup"):
            sup = elem1.attributes['name'].value
            writer.writerow({'sub': sub, 'sup': sup})


for root, dirs, files in os.walk('data/frames'):
    for file in files:
        if (file.endswith('.xml')):
            xmldoc = parse(os.path.join(root, file))
            frelation = xmldoc.getElementsByTagName("frameset")[0]
            relation = frelation.getElementsByTagName("predicate")
            writeToCSV(frelation)

你在 WriteToCSV 中一次又一次地覆盖同一个文件,可能会有如下变化:

def writeToCSV(frelation,file_id):
    csvfile = open('data'+str(file_id)+'.csv', 'w')
    fieldnames = ['sub', 'sup']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    relation = frelation.getElementsByTagName("predicate")
    for elem in relation:
        sub = elem.attributes['sub'].value
        for elem1 in elem.getElementsByTagName("sup"):
            sup = elem1.attributes['name'].value
            writer.writerow({'sub': sub, 'sup': sup})

file_id=1;
for root, dirs, files in os.walk('data/frames'):
    for file in files:
        if (file.endswith('.xml')):
            xmldoc = parse(os.path.join(root, file))
            frelation = xmldoc.getElementsByTagName("frameset")[0]
            relation = frelation.getElementsByTagName("predicate")
            writeToCSV(frelation,file_id)
            file_id+=1

如果你只想要一个 CSV 文件,你需要以追加模式打开文件,如果文件不存在,a+ 模式表示创建文件。:

def writeToCSV(frelation):
        csvfile = open('data.csv', 'a+')
        fieldnames = ['sub', 'sup']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        relation = frelation.getElementsByTagName("predicate")
        for elem in relation:
            sub = elem.attributes['sub'].value
            for elem1 in elem.getElementsByTagName("sup"):
                sup = elem1.attributes['name'].value
                writer.writerow({'sub': sub, 'sup': sup})

其他代码无需更改。

暂无
暂无

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

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