python - 从嵌套文件夹导入模块

标签 python python-2.7 import

<分区>

我有这样的文件夹结构

main_folder
|
|--done
|  |
|  |--test1
|  |--__init__.py
|
|---check.py

__init__.py:

class Tries(object):
    def __init__(self):
        print "Test"

检查.py:

from done.test1 import Tries
Tries()

错误:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-8-10953298e1df> in <module>()
----> 1 from done.test1 import Tries

ImportError: No module named done.test1 

我无法从嵌套文件夹导入模块。有什么办法可以做到这一点。

编辑:

在 Salva 的回答后我改变了我的结构

.
├── check.py
|--__init__.py(no content)
└── done
    ├── __init__.py(no content)
    └── test1
        └── __init__.py <-- this files contains your Tries class

现在也抛出同样的错误。

最佳答案

您需要在每个目录中都有一个文件 __init__.py,您希望它被视为一个包,因此您在两个 目录中都需要它:

.
├── check.py
└── done
    ├── __init__.py
    └── test1
        └── __init__.py <-- this files contains your Tries class

关于python - 从嵌套文件夹导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35267962/

相关文章:

python - 引发异常时如何使用atexit

python - 使用静态装饰器进行动态装饰

python - 为什么多处理锁定失败?

python - 未检测到 Youtube 视频位置

Oracle Import Error in 11GR2, ORA-39082 objects creating with compilation errors

python - 类型错误 : Error when calling the metaclass bases module

python - 无法从脚本访问数据库

python - 当我将 ANSI 字符串更改为 UNICODE 字符串时,函数 re.sub() 拒绝工作

templates - 如何导出/导入Netbeans模板

python - argparse 不转换默认数字参数?