[英]Unable to import module in Python
Why am I having an 'undefined bdir module' error, here is my directory, 为什么我有'未定义的bdir模块'错误,这是我的目录,
a.py a.py
bdir->bdir>module.py bdir-> bdir> module.py
in a.py 在a.py.
from bdir import *
在您的bdir文件夹中放入__init__.py
文件(甚至为空)。
Any folder without a __init__.py
file inside of the folder is not considered a module. 文件夹中没有__init__.py
文件的任何文件夹都不被视为模块。 Furthermore, if you want to import *
from a module, make sure that actually import the things you require into __init__.py
, or declare a __all__
list. 此外,如果要从模块import *
,请确保实际将所需内容导入__init__.py
,或声明__all__
列表。
Also, if you want to make a relative import, meaning that you want to import a file from the package that a module is currently in, then you do a relative import. 此外,如果要进行相对导入,意味着要从模块当前所在的包中导入文件,则执行相对导入。 So, for example, if you have: 所以,例如,如果你有:
bdir
- bdir
- __init__.py
- module.py
- a.py
In order to import anything from the bdir.module
, you have to import it like so if you are in a.py
: 要从bdir.module
导入任何内容,如果你在a.py
,你必须像这样导入它:
from .module import *
If outside the bdir
module then: 如果在bdir
模块之外,那么:
from bdir.module import *
You must create a __init__.py
file, that's how Python knows which folders are packages that can be imported using the import
. 您必须创建一个__init__.py
文件,这就是Python知道哪些文件夹是可以使用import
。 Here's the documentation : 这是文档 :
The
__init__.py
files are required to make Python treat the directories as containing packages; 需要__init__.py
文件才能使Python将目录视为包含包; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. 这样做是为了防止具有通用名称的目录(例如字符串)无意中隐藏在模块搜索路径上稍后(更深)发生的有效模块。 In the simplest case,__init__.py
can just be an empty file, but it can also execute initialization code for the package or set the__all__
variable. 在最简单的情况下,__init__.py
可以只是一个空文件,但它也可以执行包的初始化代码或设置__all__
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.