Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import a python module from a different folder with another module import in it

I have the following file structure:

main.py
Core/
    object_storage.py
    setup_logger.py

main.py:

from Core import object_storage
#rest doesn't matter

object_storage.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from setup_logger import logger
#rest doesn't matter

setup_logger.py:

import logging
import sys
Log_Format = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(stream = sys.stdout, 
                    format = Log_Format, 
                    level = logging.INFO)

logger = logging.getLogger()

When I run object_storage.py it works perfectly, but when I want to run main.py it gives me the error:

ModuleNotFoundError: No module named 'setup_logger'

I checked os.getcwd() and I think the issue is the working directory remains the root folder where I have main.py when I want to import setup_logger from Core/object_storage.py.

What is the way to solve this?

>Solution :

When Python runs your file, it adds the file’s directory to the sys.path (this is where Python looks the modules and packages).

I recommend that you always check the sys.path in these situations then you can easily find out why this error happens.

When you run main.py only it’s directory is added to the sys.path. So you can find the setup_logger with Core.setup_logger (Python knows where to find Core directory. change the object_storage.py file to:

from Core.setup_logger import logger

Up until now running main.py works perfectly but now another issue raises. This time if you run object_storage.py itself, you get the error which says:

ModuleNotFoundError: No module named 'Core'

So in order to be able to run both main.py and object_storage.py directly, consider adding the path to the main.py‘s directory (where the Core exists) to object_storage.py because this time that directory is not going to be added automatically:

# object_storage.py

import sys
sys.path.insert(0, r'PATH TO WHERE Core EXIST')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading