Looz
Looz

Reputation: 407

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:

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?

Upvotes: 3

Views: 4447

Answers (1)

S.B
S.B

Reputation: 16476

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

Upvotes: 2

Related Questions