如何将多个 XML 文件解析为多个 CSV 文件?

Posted

技术标签:

【中文标题】如何将多个 XML 文件解析为多个 CSV 文件?【英文标题】:How to parse several XML file into several CSV file? 【发布时间】:2019-11-15 16:22:47 【问题描述】:

我使用此代码解析 XML 文件,该代码适用于单个 xml 输入到单个 csv 输出。我尝试使用 glob 处理多个输入和多个 csv 输出,但我知道这是不正确的。

import glob
import xml.etree.ElementTree as et
import csv

for file in glob.glob('./*.xml'):
    with open(file) as f:
        tree = et.parse(f)
        nodes = tree.getroot()

        with open(f'f[:-4]edited.csv', 'w') as ff:
            cols = ['dateTime','x','y','z','motion','isMoving','stepCount','groupAreaId','commit']
            nodewriter = csv.writer(ff)
            nodewriter.writerow(cols)
            for node in nodes:
                values = [ node.attrib.get(kk, '') for kk in cols]
                nodewriter.writerow(values)

我应该如何更改以获得多个 csv 输出?

【问题讨论】:

您的意思是使用with open(f'file[:-4]edited.csv', 'w') as ff: 吗?当前,您正在使用文件句柄作为文件名。 得到你的答案! 【参考方案1】:

您的代码当前正在使用文件句柄来形成您的输出文件名。代替f 使用file,如下所示:

import glob
import xml.etree.ElementTree as et
import csv

for file in glob.glob('./*.xml'):
    with open(file) as f:
        tree = et.parse(f)
        nodes = tree.getroot()

        with open(f'file[:-4]edited.csv', 'w') as ff:
            cols = ['dateTime','x','y','z','motion','isMoving','stepCount','groupAreaId','commit']
            nodewriter = csv.writer(ff)
            nodewriter.writerow(cols)
            for node in nodes:
                values = [ node.attrib.get(kk, '') for kk in cols]
                nodewriter.writerow(values)

【讨论】:

【参考方案2】:

您可以创建一个文件名列表,然后在其中写入 xml 文件。如果输出文件已经在目录中,那么使用 glob 可以获得名称。如果文件不存在,下面的代码将使用给定的文件名创建

csvFileNames = ['outputfile1.csv', 'outputfile2.csv']
for file in csvFileNames:
    with open(file, 'w') as f:
        wtr = csv.writer(f)
        wtr.writerows( [[1, 2], [2, 3], [4, 5]]) # write what you want

要从目录中获取 XML 文件名,您可以尝试以下代码:

from os import listdir
filenames = listdir('.') # here dot is used because script and csv files are in the same directory, if XML files are in other directory then set the path inside listdir
xmlFileNames = [ filename for filename in filenames if filename.endswith( ".xml" ) ]

# get xml file names like this, xmlFileNames = ["abc.xml", "ef.xml"]
resultCsvFileNameList = [fname.replace(".xml", ".csv") for fname in xmlFileNames ]

【讨论】:

但是如果我有成千上万个 csv 文件要写,有没有比一个一个提到 csv 文件名更简单的方法? 你不必手动写文件名,使用glob你可以收集文件名 感谢编辑,但我的问题是我需要从 xml 文件创建 .csv 文件,显然 csv 文件还不存在。这就是为什么我想知道如何自动创建与 xml 文件名相同的 .csv 文件。

以上是关于如何将多个 XML 文件解析为多个 CSV 文件?的主要内容,如果未能解决你的问题,请参考以下文章