【问题标题】:How can I Iterate over each file in a directory using ET.parse function如何使用 ET.parse 函数遍历目录中的每个文件
【发布时间】:2019-10-05 00:56:28
【问题描述】:

当我运行下面的代码时,我只能从我的源文件夹(下面用“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 loops parsing for-loop iterator


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2019-01-16
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      相关资源
      最近更新 更多