python - 在 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 新手。
解决方案
您没有将文件路径的正确部分连接在一起,您只是将path
和filename
. 如果 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")
显然,您需要更改路径以匹配您要搜索的位置。
推荐阅读
- laravel - 未定义变量:AppServiceProvider 中的事件错误
- javascript - 如何在 xml 视图中的特定销售订单行列中添加弹出框?使用 One2ManyListView js 继承?
- c - c中移位的正确顺序
- excel - 宏将数据从一张纸粘贴到另一张纸的最后填充行中的空白列
- mysql - 如何在“使用数据库”语句中使用用户变量
- javascript - 返回一个比每个字符在字符串中出现的次数多 1 个字符的字符串
- c - 入栈问题
- php - 模型自动检查 active = 1 为什么?拉拉维尔 5.7
- java - 将 Javers 与协议缓冲区对象一起使用
- javascript - 从网页获取所有图像并以编程方式保存到磁盘(NodeJS 和 Javascript)