DimSarak
DimSarak

Reputation: 462

Python 3 -- Module not found

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?

Upvotes: 8

Views: 22123

Answers (4)

minkimeraai
minkimeraai

Reputation: 11

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')

Upvotes: 1

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10970

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.

Upvotes: 1

hygull
hygull

Reputation: 8740

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.

Upvotes: -1

keredson
keredson

Reputation: 3087

This is almost certainly a PYTHONPATH issue of where you're running your script from. In general this works:

$ ls modA/
fileAA.py  __init__.py
$ cat modA/fileAA.py 
x = 1
$ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from modA.fileAA import x
>>> x
1

You can look at sys.path to inspect your path.

Upvotes: 1

Related Questions