首页 > 解决方案 > 如何使用 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”等。

标签: xmlloopsparsingfor-loopiterator

解决方案


在您的粘贴中,意图看起来是错误的。就像输出写入在 xml_files 的 for 循环之外。


推荐阅读