Python 2.5.4 - 导入错误:没有名为 etree.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()
我在命令行运行时会收到错误信息,但直接在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这个路径下。
4 个回答
12
我遇到了同样的错误 report("ImportError: No module named etree.ElementTree")
,当我把测试文件命名为 xml.py
的时候。然后我把文件名改成其他的,比如 xmltest.py
,问题就解决了。
48
因为你原来的文件名是 C:\xml.py
把这个文件名改成其他的名字就可以了
7
你在教程中漏掉了一行很重要的内容。
import xml.etree.ElementTree as xml
这行代码让整个模块都可以用xml来代替xml.etree.ElementTree。
我正好在用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,或者还有其他奇怪的问题。