Animesh Pandey
Animesh Pandey

Reputation: 6018

Module not found but has init.py

I have the following directory structure

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

In file.py I import class Header defined in header.py using from Head.main.header import *.

I have all the __init__.py's in place but still when I run file.py I get ImportError: No module named Head.main.header.

I am using PyCharm.

How should I solve it?

Running tree I got:

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

Upvotes: 4

Views: 7827

Answers (2)

Copperfield
Copperfield

Reputation: 8510

that is because the import is trying to locate Head in the same folder tham file.py is, first you have to include the folder of head in the path of the system so the import can locate it. To do that do this:

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

put all the dirname needed until get to the folder containing Head

then do yours import normally

It may look a little ugly, but the advantage is that if you later move the folder of you proyect to other place, you don't have to change the every single sys.path.append is you do it like this sys.path.append("/folder1/folder2")

Upvotes: 0

robertkohl125
robertkohl125

Reputation: 41

Can you include the import code in file.py? See this answer as well, it might have your solution: import-error-in-python-even-after-having-init-file-and-python-path. Then tell us what worked!

Upvotes: 2

Related Questions