user10068582
user10068582

Reputation:

Python 2.7.16 - ImportError: No module named etree.ElementTree

I am making a script to perform creating and writing data to XML file. The error is no module no module name

I refer to this stackoverflow link, Python 2.5.4 - ImportError: No module named etree.ElementTree. I refer to this tutorial, https://stackabuse.com/reading-and-writing-xml-files-in-python/. I still do not understand on what is the solution. I tried to replace

"from elementtree import ElementTree"

to

"from xml.etree import ElementTree"

It still did not work.

#!/usr/bin/python
import xml.etree.ElementTree as xml
root = xml.Element("FOLDER")

child = xml.Element("File")

root.append(child)

fn = xml.SubElement(child, "PICTURE")
fn.text = "he32dh32rf43hd23"
md5 = xml.SubElement(child, "CONTENT")
md5.text = "he32dh32rf43hd23"

tree = xml.ElementTree(root)
with open(xml.xml, "w") as fh:
   tree.write(fh)

""" I expect the result to be that data is written to xml file. But I received an error shown below,

  File "./xml.py", line 2, in <module>
    import xml.etree.ElementTree as xml
  File "/root/Desktop/virustotal/testxml/xml.py", line 2, in <module>
    import xml.etree.ElementTree as xml
```ImportError: No module named etree.ElementTree

Upvotes: 2

Views: 2560

Answers (2)

Kiran Gali
Kiran Gali

Reputation: 111

etree package is provided by "ElementTree" and "lxml" both are similar but it is reported that ElementTree have bugs in python 2.7 and works great in python3. I see you are using python 2.7 so lxml will work fine for you.

try this

from lxml import etree
from io import StringIO

tree = etree.parse(StringIO(xml_file))
# incase you need to read an XML.

print(tree.getroot())

And the StringIO is from default python io package. StringIO is neccessary when you are passing file to it (I mean putting XML in a file and passing that file to parser). It's good to keep it even tough you are passing XML as a big string. all the writing operations will be same for both.

Upvotes: 1

Wei Yang
Wei Yang

Reputation: 78

import xml.etree.ElementTree as xml

and make sure you have the __init__.py file within the same folder if you use your own xml module and please avoid the path conflict.

then it will work.

Upvotes: 2

Related Questions