import from another folder in python

How to Import from Another Folder in Python

Python is a powerful language that offers many useful features. Typically, we need to import modules and packages in every python script, in order to be able to use its functions and member variables. Sometimes, you may need to import from another folder or directory in Python. In this article, we will look at how to import from another folder in Python.


How to Import from Another Folder in Python

Typically, python looks for packages in the present folder of the script being executed, and the folders listed in python’s environment PATH variable. Let us say you have main.py script in folder 1 and module.py in folder 2, and you want to import module.py in main.py.

 - Folder_1
    - main.py
 - Folder_2
     - module1.py

Let us say module.py has function hello_world(). There are two ways to do this – using sys module, and using PYTHONPATH environment variable.


1. Using sys module

You can use sys.path function to add the folder location of module to the system path, so that python will search it for the module, in case it is unable to find it in the script’s present directory. Since sys.path is a list, you can use append or insert function to add the module folder location. Here is an example to import module.py in main.py.

# importing sys
import sys
  
# adding Folder_2 to the system path
sys.path.insert(0, '/home/ubuntu/Desktop/Folder_2')

#alternatively you can use sys.path.append('/home/ubuntu/Desktop/Folder_2')

  
# importing the hello_world function 

from module1 import hello_world

...


2. Using Pythonpath

sys.path function needs to be called in all your python scripts, if you want to import module from another folder. If you need to import module in many of your scripts, then it is advisable to simply add this folder location to PYTHONPATH folder. Thereafter, you won’t need to use sys.path in any of your scripts. You can directly import the desired module and python will be able to find it for you.

Here is the command to add the folder to PYTHONPATH variable.

Linux

$ export PYTHONPATH='/home/ubuntu/Desktop/Folder_2'

You can check if it has been added correctly using echo command.

$ echo PYTHONPATH

Windows

$ set PYTHONPATH='C:\ubuntu\Desktop\Folder_2'

In this case, however, you need to have the permission to set environment variables on your system.

That’s it. In this article, we have seen how to import modules from another folder in Python. If you just want to import the module once, you can use sys.path. If you want to import it in multiple scripts, directly add the folder location to PYTHONPATH envionment variable.

Also read:

How to Enable Apache MPM Prefork
How to Change Apache Prefork to Worker
How to Enable PHP in Apache
How to Install Rspamd in Ubuntu
How to Change Wifi password from terminal

Leave a Reply

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