I'm running Python 2.5.4 on Windows and I keep getting an error when trying to import the ElementTree or cElementTree modules. The code is very simple (I'm following a tutorial):
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()
I get the error message when I run it from the cmd or but not when I directly try it from the Python interpreter.
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
Also, I checked and the module is there in C:\Python25\Lib\xml\etree
I got the same error
report("ImportError: No module named etree.ElementTree")
when naming the test file asxml.py
. And it got fixed when I renamed it to something else likexmltest.py
.You missed the very important line in the tutorial
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:
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
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
. Whenimport xml.etree.ElementTree
orxml.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 toimport etree.ElementTree
, and could not find a package or module namedetree
. I changed the name of my module to xml_parse.py and deletedmy_project_root/utilities/xml.pyc
and it worked perfectly. A simple reminder of using caution with module naming conventions.