从另一个目录导入Python模块

时间:2017-04-28 03:56:04

标签: python-3.x python-import python-3.6

我有一个python程序,它具有以下项目结构:

ProjectName
     |
     |----ProjectMain.py
     |
     |----__init__.py
     |
     |----Common
            |
            |----Dictionaries
            |         |
            |         |----Dicts.py
            |         |
            |         |----__init__.py
            |
            |----Core.py
            |
            |----LogoCreator.py
            |
            |----__init__.py

除了每个__init__.py个文件都是空的之外,每个文件的内容如下:

LogoCreator.py

def random_logo():
#    do stuff


   Core.py

from LogoCreator import random_logo
import Dictionaries.Dicts as Dicts

#do stuff


   Dicts.py

i_am_a_dictionary = {}


   ProjectMain.py

from Common.Core import *
import Common.Dictionaries.Dicts as Dicts

#do stuff


当我运行ProjectMain.py时,我收到以下错误:

Traceback (most recent call last):
  File "ProjectName\ProjectMain.py", line 1, in <module>
    from Common.Core import *
  File "ProjectName\Common\Core.py", line 1, in <module>
    from LogoCreator import random_logo
ModuleNotFoundError: No module named 'LogoCreator'

这是我第一次使用软件包,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

如果要使用random_logo方法,则必须在导入LogoCreator后使用点表示法。

from Common import LogoCreator
def create (self):
  x = self.random_logo()
  #code that generates a random logo