Python 3 -- Module not found

Viewed 19512

I have the following file structure...

 > Boo
    > ---modA
    > ------__init__.py
    > ------fileAA.py
    > ---modB
    > ------__init__.py
    > ------fileBB.py

When inside fileBB.py I am doing

from modA.fileAA import <something>

I get the following error:

from modA.fileAA import <something>
ModuleNotFoundError: No module named 'modA'

Note that the __init__.py files are empty and using Python 3.

What am I missing or doing wrong here?

4 Answers
main_package
├── __init__.py
├── modA
│   ├── fileAA.py
│   └── __init__.py
└── modB
    ├── fileBB.py
    └── __init__.py

Have an __init__.py in the root directory and then use import like

from main_package.modA.fileAA import something

Run using a driver file inside main_package then run, it'll work.

Using sys.path.append worked for me. I inspected the paths of the version which imported the package correctly and added those paths to the kernel which I was working on which had the import error. I had an issue with 2 packages, one working on anaconda and the other on Python3.7. Adding the Python3.7 paths to the anaconda kernel (Python 3) solved the issue.

I.e.

import sys
sys.path.append('...\AppData\\Roaming\\Python\\Python37\\site-packages\\win32')

As you have written your code in fileBB.py and trying to import variables/functions/classes etc. defined in fileAA.py, you actually need to do something like this:

  • First create an empty __init__.py inside Boo.

  • Then try to import like this:

    from ..modA.fileAA import <something>
    

As per my experience with writing packages, it should work fine.

Note: Please comment if it doesn't work, I will help but this should not happen.

Related