python3 : Import modules from another folder into your code

In this article we will discuss how to import modules from another folder into your code. Sometimes we create user defined modules and store it in specific folder and then we import them in our codes.

Suppose we have our folder structure like below:

module from another folder

Here “logger.py” is the module we would like to import in our code which is “mainBatch.py”. Clearly these two files are in different folders.

Before we try to import the “logger.py” module, the first thing that needs to be done is to create a file called “__init__.py” in classes folder. This file will mark the classes folder as python package directory.

Now lets move to the “mainBatch.py”. In this file the first thing we need to do is to find a way to point to classes folder. We can achieve this with below code:

from pathlib import Path
import sys
import os

path = Path(sys.path[0]) #get the current path
parentPath = path.parent #get the parent folder path of the current 

#append /classes to the parent path
pathsys.path.insert(0,str(parentPath)+"/classes") 

Above code will make sure that full path to classes folder is now available into system path. You can check this by adding a print statement

print(sys.path[0])

Since the path to classes folder is now available we can import the module. Full code below:

from pathlib import Path
import sys
import os

path = Path(sys.path[0]) #get the current path
parentPath = path.parent #get the parent folder path of the current

#append /classes to the parent path
pathsys.path.insert(0,str(parentPath)+"/classes") 

from logger import Logger # import the module

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *