8

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?

5
  • Where is the Python script? If you are running python3 fileBB.py directly then it won't look up the tree for modules. Commented Jul 27, 2017 at 15:54
  • 1
    put __init__.py in Boo ? Commented Jul 27, 2017 at 15:54
  • 1
    Run it from within the Boo directory Commented Jul 27, 2017 at 15:55
  • 1
    I've used sys.path.append('../') before the import in this scenario and it has worked in the past. Commented Jul 27, 2017 at 15:58
  • tried to add init.py at Boo but the same error Commented Jul 27, 2017 at 16:06

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

1

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

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.