首页 > 解决方案 > 在 python 中从 xml 文件中提取元素失败

问题描述

我的代码有一个很大的问题,我希望有人可以在这里提供帮助。我需要从位于多个子目录中的 xml 文件中提取特定元素。我编写了一个脚本来遍历所有文件夹和子目录以获取 xml 文件并提取该元素并将其保存在单独的文件中。代码如下所示:

import os

import csv

import itertools

import pandas as pd

from xml.etree import ElementTree as ET

path = "D:/..."

file = open('out.csv', 'w')

for root, dirs, files in os.walk(path):
    for filename in files:
        if not filename.endswith(".xml"): continue
        if filename.endswith(".xml"):
            fullname = os.path.join(path, filename)
            tree = ET.parse(fullname)
            root = tree.getroot()
            for row in root.iter('p'):
                file.write(row.text)

我得到的错误是“FileNotFoundError: [Errno 2] No such file or directory: 'D:/..\0000233.xml”

即使文件存在并且有内容。

我做错了什么?我会非常感谢帮助和提示,因为我是 python 新手。

标签: pythonxmlelementtree

解决方案


您没有将文件路径的正确部分连接在一起,您只是将pathfilename. 如果 xml 文件存在于 的子目录中path,您将找不到该文件。您当前的方法仅适用于路径指定的文件夹内的文件。

下面的方法使用 pathlib 和它的glob方法递归搜索目录和子目录中的所有 xml 文件。这使您不必检查每个文件以查看它们是否具有.xml文件扩展名,因为它只会返回 xml 文件。Pathlib 还返回文件的绝对路径,而不必将不同的部分连接在一起。

import os
from pathlib import Path
from xml.etree import ElementTree as ET

path = Path(r"C:\\Users\\MyFiles\\")

file = open('out.csv', 'w')
print(path)

for file_path in path.glob('**/*.xml'):
    try:
        tree = ET.parse(file_path)
        root = tree.getroot()
        for row in root.iter('p'):
            file.write(row.text)
            print(row.text)
    except ET.ParseError:
        print(f"Couldn't parse {file_path} - Ignoring")

显然,您需要更改路径以匹配您要搜索的位置。


推荐阅读