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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:39:47  来源:igfitidea点击:

Python Error : ImportError: No module named 'xml.etree'

pythonxmlpython-3.x

提问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 文件夹中看到:

enter image description here

在此处输入图片说明

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.pyor a directory xmlwith a file __init__.pyin it from your current directory and try again. Python will search the current directory first when importing modules. A file named xml.pyor a package named xmlin 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 *.pyfile is around, you can savely delete the corresponding *.pycfile because Python will re-create it upon import of the *.pyfile.

正如 KeshV 在评论中指出的那样,您还需要删除文件xml.pyc(如果存在)。在 Python 2 中,它将与xml.py. 在 Python 3 中,它将位于子目录中__pycache__。一般情况下,只要*.py文件还在,就可以安全地删除相应的*.pyc文件,因为Python会在导入*.py文件时重新创建它。