While working on big projects we may confront a situation where we want to import a module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module from another directory.
Note: A module is just a Python program that ends with .py extension and a folder that contains a module becomes a package.
Let’s suppose, we have two different folders, one contains main.py which is our main Python file where we want to import module1 from Folder_2.
- Folder_1 - main.py - Folder_2 - module1.py
Module1 contains two functions called add and odd_even. The function add will takes two arguments and return the addition of them. The odd_even function will take only one argument and print Even if the number is even or print Odd if the number is odd.
If we simply try to import module1 from Folder_2, we will be encountering the following error.
ModuleNotFoundError, because by default python interpreter will check for the file in the current directory only, and we need to set the file path manually to import the modules from another directory. We can do this using various ways. These ways are discussed below in detail.
Using sys module
We can use sys.path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that python can also look for the module in that directory if it doesn’t found the module in its current directory. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path.
Using PYTHONPATH environment variable
Similarly, if you don’t want to use the sys module to set the path of the new directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.
In Linux, we can use the following command in the terminal to set the path:
In Windows system :
To see if PYTHONPATH variable holds the path of the new folder, we can use the following command:
Suppose we have a directory structure like this:
- project - Folder_1 - main.py - Folder_2 - subfolder - new.py
Now, you want to import the new.py module from Folder_2 to our project’s Folder_1 main.py file.
from project.folder.subfolder.filename import functionname
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course