close

How to import a module from a different folder?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to import a module from a different folder in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to import a module from a different folder?

  1. How to import a module from a different folder?

    Unfortunately, Python will only find your file if your file is in the systems path. But fear not! There is a way around this!

  2. import a module from a different folder

    Unfortunately, Python will only find your file if your file is in the systems path. But fear not! There is a way around this!

Method 1

Firstly, this import statement:

from models import some_model

should be namespaced:

# in myproject/backend/backend.py or myproject/api/api.py
from myproject.models import some_model

Then you will need to get the directory which contains myproject, let’s call this /path/to/parent, into the sys.path list. You can do this temporarily by setting an environment variable:

export PYTHONPATH=/path/to/parent

Or, preferably, you can do it by writing a setup.py file and installing your package. Follow the PyPA packaging guide. After you have written your setup.py file, from within the same directory, execute this to setup the correct entries in sys.path:

pip install --editable .

Method 2

Unfortunately, Python will only find your file if your file is in the systems path. But fear not! There is a way around this!

Using python’s sys module, we can add a directory to the path just while Python is running, and once Python stops running, it will remove it from the path.

You can do this by:

import sys
sys.path.insert(0, '/path/to/application/app/folder')
import [file]

It is important to import sys and set the directory path before you import the file however.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read