Python 错误:ImportError:没有名为“xml.etree”的模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33633954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Error : ImportError: No module named 'xml.etree'
提问by AbtPst
I am simply trying to parse an XML file:
我只是想解析一个 XML 文件:
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
but this gives me:
但这给了我:
import xml.etree.ElementTree as ET
ImportError: No module named 'xml.etree'
I am using Python 3.5. I have tried to same code with Python 2.7 and 3.4 but I always get this error. I thought that the XML libraries come as standard. Also, I can see that in my Lib folder:
我正在使用 Python 3.5。我曾尝试使用 Python 2.7 和 3.4 编写相同的代码,但我总是收到此错误。我认为 XML 库是标准的。另外,我可以在我的 Lib 文件夹中看到:
So why can't it pick up the module? I am really confused. Do I have to make some change in an environment variable somewhere?
那么为什么它不能接模块呢?我真的很困惑。我是否必须在某处对环境变量进行一些更改?
Please help.
请帮忙。
采纳答案by Mike Müller
Remove the file xml.py
or a directory xml
with a file __init__.py
in it from your current directory and try again. Python will search the current directory first when importing modules. A file named xml.py
or a package named xml
in the current directory shadows the standard library package with the same name.
从当前目录中删除文件xml.py
或包含文件的目录xml
,__init__.py
然后重试。Python 在导入模块时会先搜索当前目录。当前目录中xml.py
命名的文件或命名的包会xml
隐藏同名的标准库包。
As pointed out in a comment by KeshV, you also need to remove the file xml.pyc
, if it exists. In Python 2 it will be in the same directory as xml.py
. In Python 3 it will be in the sub directory __pycache__
. In General, as long as the *.py
file is around, you can savely delete the corresponding *.pyc
file because Python will re-create it upon import of the *.py
file.
正如 KeshV 在评论中指出的那样,您还需要删除文件xml.pyc
(如果存在)。在 Python 2 中,它将与xml.py
. 在 Python 3 中,它将位于子目录中__pycache__
。一般情况下,只要*.py
文件还在,就可以安全地删除相应的*.pyc
文件,因为Python会在导入*.py
文件时重新创建它。