Python 2.5.4 - ImportError: No module named etree.ElementTree

强颜欢笑 提交于 2019-11-29 02:05:18
manifest

You missed the very important line in the tutorial

import xml.etree.ElementTree as xml

This makes xml.etree.ElementTree now known as xml throughout the module.

I happen to have python 2.5.4 and I have verified that the same code you have above works:

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$ 

So check and make sure you're running python 2.5.4 and if you are try reinstalling. The problem is not that it's python 2.5.4 or your code. It's some installation problem, you're running a different version of python, or there's some other strange problem.

Because your original file name is C:\xml.py

Change the file name to any other name

kyle

I got the same error report("ImportError: No module named etree.ElementTree") when naming the test file as xml.py. And it got fixed when I renamed it to something else like xmltest.py.

I had a funny situation, which may or may not be similarly to this and found my solution. I created my own module for parsing xml files. I put it in my_project_root/utilities/xml.py. When import xml.etree.ElementTree or xml.etree from within this module I would get the error in the title of this posting. It was searching in itself, so from within xml.py it was attempting to import etree.ElementTree, and could not find a package or module named etree. I changed the name of my module to xml_parse.py and deleted my_project_root/utilities/xml.pyc and it worked perfectly. A simple reminder of using caution with module naming conventions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!