遍历 xml 文件列表?

Looping through list of xml-files?

我正在尝试创建一个循环遍历 xml 文件列表并从文件中提取某些元素的程序:

from os import listdir, path
import xml.etree.ElementTree as ET

mypath = 'C:\myfolder'

files = [f for f in listdir(mypath) if f.endswith('.xml')]

for file in files:
    tree = ET.parse(file)
    root = tree.getroot()

ns = {namespaces}

def myfunction():
    if 'something' in root.tag:
        filename = path.splitext(file)[0]
        var1 = root.find('./element1', ns)
        var2 = root.find('./element2', ns)

        row = [
            var1.text,
            var2.text
            ]

    return row   

如果我调用该函数,上面的代码 returns 包含 var1、var2(来自最后一个文件)的列表。我定义这个函数的原因是有不同类型的 xml-files 具有不同的元素名称,所以我将为每种文件类型创建一个函数。

现在我想创建一个 table,其中每个文件的输出是一行,即:

filename1, var1, var2
filename2, var1, var2
ect.

最好将 table 导出到 csv 文件。我该怎么做?

编写 CSV 文件的最简单方法是使用 Standard CSV。 要写入 CSV 文件,只需打开文件并使用默认编写器即可:

import csv
from os import listdir, path
import xml.etree.ElementTree as ET

mypath = 'C:\myfolder'

files = [f for f in listdir(mypath) if f.endswith('.xml')]

for file in files:
    tree = ET.parse(file)
    root = tree.getroot()

ns = {namespaces}

def myfunction():
    if 'something' in root.tag:
        filename = path.splitext(file)[0]
        var1 = root.find('./element1', ns)
        var2 = root.find('./element2', ns)

        row = [
            var1.text,
            var2.text
            ]

        # Open the file and store the data
        with open('outfile.csv', 'a', newline='') as csvfile:
            csv_writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            csv_writer.writerow(row)

    return row   

注意 <a href="https://docs.python.org/3.6/library/csv.html#csv.writer" rel="nofollow noreferrer">csf.writer</a> 接收一个列表作为参数。