Python 2.5.4 - ImportError:没有名为etree.ElementTree的模块

Jen*_*Jen 9 python import elementtree

我正在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()
Run Code Online (Sandbox Code Playgroud)

当我从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
Run Code Online (Sandbox Code Playgroud)

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

小智 46

因为您的原始文件名是C:\ xml.py

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

  • 哦上帝的痛苦.另外不要忘记删除"xml.pyc"文件! (16认同)
  • 我刚遇到了同样的问题.命名我的脚本xml.py似乎是合乎逻辑的,因为我将第一次使用它来试用xml库来学习它们.没想到脚本的名字与Python命名空间搞砸了.:)感谢您注意到这一点. (2认同)

小智 10

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


man*_*est 7

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

import xml.etree.ElementTree as xml
Run Code Online (Sandbox Code Playgroud)

这使得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$ 
Run Code Online (Sandbox Code Playgroud)

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


Fur*_*tor 5

我有一个有趣的情况,可能与此相似或不同,并找到了我的解决方案.我创建了自己的模块来解析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,它完美地工作.简单提醒一下使用模块命名约定时要小心.