【问题标题】:Python 2.5.4 - ImportError: No module named etree.ElementTreePython 2.5.4 - ImportError:没有名为 etree.ElementTree 的模块
【发布时间】:2010-06-18 20:57:29
【问题描述】:

我在 Windows 上运行 Python 2.5.4,并且在尝试导入 ElementTree 或 cElementTree 模块时不断收到错误消息。代码很简单(我在跟着教程):

import xml.etree.ElementTree as xml

root = xml.Element('root')
child = xml.Element('child')
root.append(child)
child.attrib['name'] = "Charlie"
file = open("test.xml", 'w')
xml.ElementTree(root).write(file)
file.close()

当我从 cmd 运行它时,或者当我直接从 Python 解释器尝试它时,我收到错误消息。

Traceback (most recent call last):  
File "C:\xml.py", line 31, in <module>
  import xml.etree.ElementTree as xml   
File "C:\xml.py", line 31, in <module>
  import xml.etree.ElementTree as xml
ImportError: No module named etree.ElementTree

另外,我检查了一下,模块在 C:\Python25\Lib\xml\etree 中

【问题讨论】:

  • 运行您发布的代码时,您不会在主题中收到错误消息。您会从import etree.ElementTree 收到该消息。寻求帮助时,复制/粘贴您的代码和回溯和错误消息,不要从内存中输入。
  • 您已经更改了显示的代码,但它仍然不会在问题的主题中产生错误消息。事实上,它似乎工作。除了使用“文件”作为变量名之外,它看起来还可以。你还有问题吗?如果是这样,是什么?如果没有,您应该刚刚编辑您的问题,以便它反映原始问题是什么。
  • 如果解释器工作,而 cmd 没有,是否有可能从 cmd 运行旧版本的 python?
  • 我检查过了,但我只安装了一个版本的 Python。

标签: python import elementtree


【解决方案1】:

因为你原来的文件名是C:\xml.py

将文件名更改为任何其他名称

【讨论】:

  • 天哪,痛苦。另外不要忘记删除“xml.pyc”文件!
  • 我刚刚遇到了完全相同的问题。将我的脚本命名为 xml.py 似乎是合乎逻辑的,因为我打算第一次使用它来尝试 xml 库来学习它们。没想到脚本的名称与 Python 命名空间有关。 :) 感谢您注意到这一点。
【解决方案2】:

我在将测试文件命名为xml.py 时遇到了同样的错误report("ImportError: No module named etree.ElementTree")。当我将它重命名为 xmltest.py 之类的其他名称时,它得到了修复

【讨论】:

    【解决方案3】:

    你错过了教程中非常重要的一行

    import xml.etree.ElementTree as xml
    

    这使得 xml.etree.ElementTree 现在在整个模块中都称为 xml。

    我碰巧有 python 2.5.4,我已经验证你上面的代码可以工作:

    user@Comp test$ cat test.py 
    import xml.etree.ElementTree as xml
    
    root = xml.Element('root')
    child = xml.Element('child')
    root.append(child)
    child.attrib['name'] = "Charlie"
    file = open("test.xml", 'w')
    xml.ElementTree(root).write(file)
    file.close()
    
    user@Comp test$ /usr/bin/python2.5 --version
    Python 2.5.4
    user@Comp test$ /usr/bin/python2.5 test.py 
    user@Comp test$ cat test.xml 
    <root><child name="Charlie" /></root>user@Comp test$ 
    

    所以检查并确保您正在运行 python 2.5.4,如果您尝试重新安装。问题不在于它是 python 2.5.4 或您的代码。是安装问题,你运行的是不同版本的python,或者是其他一些奇怪的问题。

    【讨论】:

    • @Jen:发布您运行的实际代码、回溯和错误消息。 “不识别模块”是模棱两可的。
    • 谢谢!我最终下载了 effbot.org ElementTree 包并安装了它。它现在可以工作了,但我仍然不知道为什么原来的库不能工作......
    【解决方案4】:

    我遇到了一个有趣的情况,可能与此类似,也可能不同,并找到了我的解决方案。我创建了自己的模块来解析 xml 文件。我把它放在my_project_root/utilities/xml.py。当 import xml.etree.ElementTreexml.etree 在此模块中时,我会在此帖子的标题中看到错误。它本身正在搜索,因此它在 xml.py 中尝试搜索 import etree.ElementTree,但找不到名为 etree 的包或模块。我将模块的名称更改为 xml_parse.py 并删除了my_project_root/utilities/xml.pyc,它运行良好。小心谨慎地使用模块命名约定的一个简单提醒。

    【讨论】:

    • 是的,你是对的,我替换了名称,然后删除了 .pyc 文件,它就可以工作了。这个问题很有趣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 2015-12-09
    • 2012-01-26
    • 2020-12-15
    • 2015-11-17
    • 2016-07-24
    • 2017-07-15
    相关资源
    最近更新 更多