[英]How to import python-file from another folder and sub-folder
Now i'm working on Python 3.6.8, Now i'm got stuck about import file. 现在,我正在使用Python 3.6.8,现在我被导入文件卡住了。 It's can't work 没用
├── db
│ ├── commit.py
│ ├── config.py
│ ├── database.ini
│ └── __init__.py
└── main.py
This my code structure. 这是我的代码结构。 for each file , 对于每个文件,
#commit.py
from config import config
class Commit():
#many function
#some process. Which use package from config
#config.py
class config():
#some process.
#database.ini
#It's text file
#__init__.py
import commit
import config
#main.py
from db import commit
from db import config
class Main():
#many function
#include calling commit function
if __name__=="__main__":
#work with main function
But my program still error. 但是我的程序仍然错误。 When i run main.py and This below is error message. 当我运行main.py时,这是错误消息。
db/__init__.py", line 1, in <module>
import commit
ModuleNotFoundError: No module named 'commit'
Why it can't work? 为什么它不起作用? because is Python 3+ ? 因为是Python 3+? how to fix this. 如何解决这个问题。
The following structure should works: 以下结构应该起作用:
# main.py
from db.commit import *
from db.config import *
class Main():
#many function
#include calling commit function
if __name__== "__main__":
#work with main function
I suppose that you need to import everything from commit and config file. 我想您需要从提交和配置文件中导入所有内容。 But if you need just the Commit class or the config class you can modify code like the following: 但是,如果只需要Commit类或config类,则可以修改如下代码:
from db.commit import Commit
from db.config import config
Then other files 然后其他文件
# init.py
# no imports
Remove imports from init.py 从init.py中删除导入
# config.py
class config():
#some process.
config.py it's fine like your version config.py就像您的版本一样
# commit.py
from .config import *
class Commit():
#many function
#some process. Which use package from config
In this way should works correctly. 这样应该可以正常工作。
edit after comment 评论后编辑
If from main.py, you import functions contained in commit.py module and in commit.py module you import functions contained in main.py module you will have circular imports. 如果从main.py导入了commit.py模块中包含的函数,并且在commit.py模块中导入了main.py模块中包含的函数,则将进行循环导入。
In order to fix it you should organized the project structure in another way. 为了修复它,您应该以其他方式组织项目结构。
For example you can move Main class in another file and then import it in both, main.py and commit.py. 例如,您可以将Main类移动到另一个文件中,然后将其导入main.py和commit.py中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.