Sushodhan
Sushodhan

Reputation: 410

How to resolve ModuleNotFoundError?

I want to import abc.py in main.py and abc.py itself imports xyz.py and pqr.py. Following is my project structure:

main_folder
    |
    +--main.py
    |
    +--inside_folder
        |
        +--sub_folder
            |
            +--abc.py
            |
            +--xyz.py
            |
            +--subsub_folder
                |
                +--pqr.py

For doing so: I have written the following lines in main.py: from inside_folder.sub_folder import abc And abc.py contains

from inside_folder.sub_folder.subsub_folder import pqr 
from inside_folder.sub_Folder import xyz

I also tried importing without the inside_folder.sub_folder part from the abc.py file, however doing so it reports ModuleNotFoundError.

Please help me resolve this problem.

Note: I have added init.py to all the folders. Still the error cannot be resolved.

Upvotes: 0

Views: 150

Answers (2)

jaswanth
jaswanth

Reputation: 525

If you are using python2 you won't find any problem with the above folder structure if every folder has __init__.py file with below code main.py

from inside_folder.sub_folder import abc

abc.py

from subsub_folder import pqr 
import xyz

but if you are using python 3 you need to change your abc.py to

from .subsub_folder import pqr 
from . import xyz

Upvotes: 1

Masklinn
Masklinn

Reputation: 42207

  • your packages (folders acting as a single python namespace) should probably have a __init__.py file to declare them as packages, though IIRC it's not quite necessary anymore in some cases it's easier to just do it
  • from inside_folder.sub_folder import abc is completely wrong, following PEP 328 this tells Python to look for a top-level inside_folder. You need to use a relative import here so Python looks for a sibling to the importing file aka from .inside_folder.sub_folder
  • though that assume you're completely outside the tree you're showing us and doing from main_folder import main.py or running python -mmain_package.main, the PYTHONPATH will be set up differently otherwise
  • the structure you show does not match your import, abc.py is next to sub_folder, not inside it

Upvotes: 1

Related Questions