简体   繁体   English

如何从目录导入其他python代码?

[英]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! 我在哪里弄错了!

If you want to import config.py with importing child you need to define child as a package. 如果要导入config.py并导入child config.py ,则需要将child定义为包。

To do so you need to create an __init__.py file in your child directory. 要做到这一点,你需要创建一个__init__.py在文件中child目录。

Check this about packages 检查这个

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

Read about modules and packages here . 在这里阅读模块和包。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM