[英]How do I import other python code from a directory?
I'm very new to python and I have a directory structure like this: 我是python的新手,我有一个像这样的目录结构:
root
--child
-----config.py
example.py
In example.py
I just tried: 在
example.py
我尝试过:
import child
but that doesn't seems to be working. 但这似乎不起作用。
Where I'm making the mistake! 我在哪里弄错了!
Do you have a __init__.py
file in root/child/
directory? 你在
root/child/
目录中有__init__.py
文件吗? After creating this file you should be able to do this: 创建此文件后,您应该能够这样做:
import child.config
or 要么
from child import config
You can also import multiple modules from child directory like this: 您还可以从子目录导入多个模块,如下所示:
from child import first, second, third
Your directory should have init .py so that python will understand it is a package. 你的目录应该有init .py,这样python就会明白它是一个包。 So the directory structure would be like
所以目录结构就像
root
__init__.py
child
__init__.py
config.py
example.py
import root.child
note, you should import root.child
not child
. 请注意,您应该导入
root.child
而不是child
。
Create an empty __init__.py
file in same directory with config.py
. 使用
config.py
在同一目录中创建一个空的__init__.py
文件。 This is required for importing files like a package. 这是导入包等文件所必需的。
Then you can import it. 然后你可以导入它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.