找不到模块但有init.py

时间:2015-12-07 23:49:36

标签: python importerror

我有以下目录结构

Head --
      |--Data
      |--main
            |-- header.py
            |-- __init__.py
      |--dir1
            |-- file.py
      |--dir2
      |--dir3
      |-- __init__.py

file.py我使用class Header导入header.py中定义的from Head.main.header import *

我已经准备好所有__init__.py了,但是当我运行file.py时,我得到ImportError: No module named Head.main.header

我正在使用PyCharm。

我该如何解决?

正在运行tree

F:\PyCharmProjects\TestDir>tree
Folder PATH listing for volume MISC
Volume serial number is 0FCE-123A
F:.
├───.idea
├───Data
│   └───small
├───Head
    ├───dir1
    └───main

2 个答案:

答案 0 :(得分:1)

您可以在file.py中包含导入代码吗?也请看这个答案,它可能有你的解决方案:import-error-in-python-even-after-having-init-file-and-python-path。然后告诉我们什么有用!

答案 1 :(得分:1)

这是因为导入试图将head放在tham file.py所在的文件夹中,首先你必须在系统路径中包含head文件夹,以便导入可以找到它。要做到这一点:

import sys,os
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) 

将所需的所有dirname放到包含Head

的文件夹中

然后你的正常导入

它可能看起来有点难看,但优点是如果你以后将proyect的文件夹移动到其他地方,则不必更改每一个sys.path.append你是这样做的sys.path.append("/folder1/folder2") {1}}

相关问题