Bee Smears
Bee Smears

Reputation: 803

ImportError: No Module Named <parent dir>

I am trying to learn programming through Python, so I apologize in advance if this is an absurdly simple question.

I am attempting to simplify my convoluted directory structure and utilize some of Python's code-reuse features, I have encountered what is for me an inexplicable ImportError error. For the past several hours I've been reading about Python's import, module, and package features (here, here, here, and here among others), yet I remain unable to solve this (seemingly) simple error.

Here is the problem.

I have one directory (dir), within which resides one sub-directory (subdir). Each directory includes a few files. Thus, my overall directory structure looks like the following:

dir/
    __init__.py
    draw_lib.py
    subdir/
        __init___.py
        drawing.py

In my drawing.py file, I attempt to import draw_lib.py with the following line: from dir import daw_lib.py. It results in an ImportError: No module named dir. Can anyone provide a quick explanation for why my drawing.py file can't find my dir directory? Thank you for any assistance. I'm completely lost and would really like to improve my code reuse and directory structure once and for all.

Upvotes: 18

Views: 16869

Answers (2)

cpb2
cpb2

Reputation: 816

You are initially executing draw_lib.py. So the 'root directory' is / throughout the program.

Then, when you attempt 'from dir import draw_lib.py' in drawing.py it wont work because the root directory is still / and not dir/.

import draw_lib

Will work in drawing.py.

Example:

/
    __init__.py
    main.py
    test/
        __init___.py
        case.py

In main.py, put this:

import test.case

print('main.py')

if __name__ == "__main__":
        test.case.test()

In test/case.py, put this:

import main

def test():
        print('case.py')

My output:

main.py
main.py
case.py

As you can see, I imported main.py from a nested file. You'll see main.py two times. Once for the initial startup the second time when you import it in case.py.

Upvotes: 8

Avinash Yadav
Avinash Yadav

Reputation: 1

for reference please refer to this link, https://askubuntu.com/a/1163934/1748542

just add the lines of code mentioned in the linked answer to the root main.py or xyz.py or any such file. It should work like charm

eg:

parentdir
  |
  __init__.py
  main.py
  |
  subdir
    |
    __init__.py
    a.py

main.py

import os, sys

#Following lines are for assigning parent directory dynamically.

dir_path = os.path.dirname(os.path.realpath(__file__))

parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))

sys.path.insert(0, parent_dir_path)

from parentdir.subdir import a

Done your error is resolved

Upvotes: -1

Related Questions