xml - 如何使用 ET.parse 函数遍历目录中的每个文件
问题描述
当我运行下面的代码时,我只能从我的源文件夹(下面用“myfilepath”表示)中成功解析一个 xml 文件(使用指定的 xslt 文件)。尽管此源文件夹中有 10 个 xml 文件,但仍然如此。
我已经尝试过 os.dir 和 glob 但似乎都没有成功遍历文件夹中的每个 xml 文件
任何帮助将不胜感激!
import lxml.etree as ET
import pandas as pd
import glob
xml_path = (/"myfilepath")
xslt = (/"myfilepath/results_stylesheet.xsl")
#routine to define pathway to open multiple files
xml_files = glob.glob(xml_path + "/*.xml")
cntr = 1
#perform our parsing operations on all xml files in the named xml_file path above
for file in xml_files:
with open(xml_files, 'r', encoding="utf-8") as content:
data = open(xslt)
xslt_content = data.read()
xslt_root = ET.XML(xslt_content)
transform = ET.XSLT(xslt_root)
for file in xml_files:
dom = ET.parse(content)
result = transform(dom)
with open("Parsed" + str(cntr) + '.csv','w')as outputfile:
outputfile.write(str(result))
outputfile.close()
cntr +=1
我希望代码循环遍历源文件夹中的每个 xml 文件,使用 xslt 样式表进行解析,然后将解析后的文件保存到与源文件夹相同的文件夹中的新 csv 文件中。我希望每个解析的文件都有一个命名约定,如“Parsed1.csv”、“Parsed2.csv”等。
解决方案
在您的粘贴中,意图看起来是错误的。就像输出写入在 xml_files 的 for 循环之外。
推荐阅读
- python - 在长语句中省略重复
- reactjs - 反应:承诺完成后触发渲染
- google-assistant-sdk - 是否可以使用 google-assistant-sdk 静音/禁用错误响应?
- kotlin - 将一种类型的 Observable 转换为另一种类型
- angular - 推到角度的可观察变量
- html - power shell 命令 get-content 和 add-content 的问题
- algorithm - 存储数据库记录的数据结构
- opencv - 尝试使用 OpenCv 的内置人脸检测器检测人脸
- python - IndexError:标量变量的索引无效。(当逐行比较 int 值与数据框的列条目时)
- python - Matplotlib 传送多个艺术家