views:

311

answers:

1

Hi, 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 import xml.etree.ElementTree as xml
File "C:\xml.py", line 31, in 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

Thanks!!

+2  A: 

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. Good luck.

manifest
Thanks :) That is a typo... but even then it doesn't recognize the module...
Jen
@Jen: Post the actual code that you ran, the traceback, and the error message. "doesn't recognise the module" is ambiguous.
John Machin
Thanks! I ended up downloading effbot.org ElementTree package and installing it. It is working now, but I still have no idea why the original library wasn't working...
Jen