python - "instance has no attribute ' iter '"无法从命令行工作

标签 python xml elementtree

我最近开始使用 Python 编辑 XML,但我仍然发现它非常棘手......

现在我完成了脚本并首先手动测试了它。有效。 然后我尝试完全运行该脚本,但收到了以前没有发生过的错误。

我在这里提供了一个最小的例子:

import glob
import os
import sys
import xml.etree.ElementTree as ET

curgraph = "somefolder/somefolder/editedGraphPath_full.xml"   
tree = ET.parse(curgraph)
root = tree.getroot()
i=0
for file in root.iter('file'):
  i = i+1
  print i

如果我在 Python 中逐行运行此代码,一切都会正常工作。但是,如果我通过命令行运行它,则会收到此错误:

Traceback (most recent call last):
  File "/somefolder/somefolder/test.py", line 12, in <module>
    for file in root.iter('file'):
AttributeError: _ElementInterface instance has no attribute 'iter'

我尝试使用一些相关的问题,但我还没有发现任何有用的东西。

最佳答案

使用root.findall(..)

import glob
import os
import sys
import xml.etree.ElementTree as ET

curgraph = "somefolder/somefolder/editedGraphPath_full.xml"   
tree = ET.parse(curgraph)
root = tree.getroot()
i=0
for file in root.findall('file'):
  i = i+1
  print i

关于python - "instance has no attribute ' iter '"无法从命令行工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47013605/

相关文章:

python - 使用python在excel中转​​换dicom标签时出错

python - 如果找到特定字符串则删除行 Python

python - 使用 etree 在 xml 中查找节点值

python - 如果 dict.key 等于同一父级中的其他 XML 节点,则将 ET.SubElement.text 设置为 dict.value

python - 将 XML 子元素解析回字符串

python - 告诉 urllib2 使用自定义 DNS

python networkx - 通过着色标记边缘以绘制图形

xml - 在 XML 中将元素节点作为文本节点的兄弟节点是错误的吗?

android - 在 Android 中删除 xml 字符串

xml - 如何将一个 XSD 的 XML 转换为另一种非常相似但具有不同 XSD 文件的 XML 格式?