【问题标题】:How to read all xml files one by one and process them one by one如何将所有xml文件一个一个读取并一个一个处理
【发布时间】:2018-04-25 08:57:13
【问题描述】:

我在 jupyter notebook 上解析 xml 文件,我用这段代码打开一个文件:

from lxml import etree as ET
tree = ET.parse('C:\Users\mysky\Documents\Decoded\F804187.xml')
root = tree.getroot()

然后我使用 xpath 和 pandas 进行一些处理,例如我这样做:

CODE = [ ]
for errors in root.findall('.//Book/Message/Param/Buffer/Data/Field[11]'):
    error_code = errors.find('RawValue').text
    if error_code is not None:
        CODE.append(error_code)  

我有大约 10 个类似的小代码块用于提取我的数据,最后我将我的数据框保存在 CSV 文件中。

我有很多 xml 文件,我想一个一个地读取我的 Decoded 目录中的所有文件,然后也一个一个地处理它们,并将每个结果附加到我的 CSV 文件中。

谢谢!

【问题讨论】:

    标签: python xml pandas elementtree


    【解决方案1】:

    要列出目录中的所有xml 文件,您可以使用for example glob (second answer)

    它可能看起来像这样:

    import glob
    
    files = glob.glob('C:\Users\mysky\Documents\Decoded\*.xml')
    
        for file in files:
            tree = ET.parse(file)
            root = tree.getroot()
            CODE = [ ]
            for errors in root.findall('.//Book/Message/Param/Buffer/Data/Field[11]'):
                error_code = errors.find('RawValue').text
                if error_code is not None:
                    CODE.append(error_code)  
    

    【讨论】:

    • 感谢@Qback,它有效。但是当我运行其他代码来处理我的 xml 数据时,它只需要第一个文件。那么如何通过一个一个处理文件的循环来做到这一点。例如,如果我有 5 个这样的代码块:CODE = [ ] for errors in root.findall('.//Book/Message/Param/Buffer/Data/Field[11]'): error_code = errors.find('RawValue').text if error_code is not None: CODE.append(error_code) 我希望为每个文件执行 1、2、3、4 和 5 代码,然后重新启动下一个文件,直到我的文件列表末尾。
    • 为什么不定义一个函数来组合这5个代码块呢?
    猜你喜欢
    • 2013-04-07
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多