【问题标题】:How not to load the whole document, but line by line - xml, python, using xml.etree.ElementTree如何不加载整个文档,而是逐行加载 - xml,python,使用 xml.etree.ElementTree
【发布时间】:2020-02-10 09:17:03
【问题描述】:

我使用了 xml.etree.ElementTree 库,'for' 循环,理论上应该逐行读取。

不幸的是,这可能不是,因为在执行脚本后它会收到消息'Killed',所以脚本不会逐行读取。任何人都可以帮助我,提出一些建议。

我是初学者。

这是我的代码:

from xml.etree import ElementTree

file_name = 'input.xml'
full_file = os.path.abspath(os.path.join('data', file_name))

dom = ElementTree.parse(full_file)
root = dom.getroot()

for offer in root.findall('offer'):
    for category in offer.findall('category'):
        if category.text == 'f':
            a = ElementTree.SubElement(offer, 'freedelivery')
            a.text = 'true'
    dom.write(output.xml) ```

【问题讨论】:

  • input.xml 文件很大吗?
  • @mzjn 是的,2gb。
  • ElementTree.parse(full_file) 将整个文件读入内存。有一些方法可以避免这种情况,例如使用iterparse() 方法。首先查看有关处理大型 XML 文件的类似问题:stackoverflow.com/search?q=%5Bpython%5D+xml+large+file

标签: python xml elementtree xml.etree


【解决方案1】:

我对您的代码有以下评论:

  1. dom = ElementTree.parse(full_file) 读取整个输入文件 (不是逐行)。

  2. 你的 2 个嵌套循环:

    for offer in root.findall('offer'):
        for category in offer.findall('category'):
    

    可以用单个循环替换:

    for category in root.findall('offer/category'):
    
  3. 编写更新的 dom 树的指令应该在 outside 第一个 for 循环(删除它的缩进)。

  4. 最后,可能是您的代码失败的基本原因是 输出文件名应加引号,因此将其更改为dom.write('output.xml')。 否则会出现执行错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 2015-08-07
    • 1970-01-01
    相关资源
    最近更新 更多