Python – Import module outside directory

22 Mar, 2022
Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module into that file. If the module exists in the same directory as the file, we can directly import it using the syntax import module_name. But if it exists in a different directory we cannot directly import it. In this article, we will discuss various ways in which modules can be imported from outside the directory.
Our directory tree will be as follows:
D :\projects\base
|__main.py   
|__app:
      |__modules
           |___mod.py
We have a folder named ‘base’ in D:\projects and in the base folder we have a folder named app. The base directory contains main.py from which we will import the module. The app folder contains another folder named modules which contains mod.py which is the module that needs to be imported.
We will keep the code of both files as simple as possible for a better explanation:
mod.py:
Python
# defining a function hello()def hello():       # printing the string 'hello geeks!'    print('hello geeks!')
Now we will import the module mod.py and call its function hello in main.py using various methods. 
The sys.path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.path so that for importing python searches mod.py in its directories and finds it to successfully import it. The code for this method will be:
Python
# importing the sys moduleimport sys         # appending the directory of mod.py# in the sys.path listsys.path.append('D:/projects/base/app/modules')        # now we can import modimport mod    # calling the hello function of mod.pymod.hello()
Output:
hello geeks!
As we have already discussed, sys.path contains the list of all directories that will be searched for the module. A better way is to insert the directory of the module at position 1 so that it is loaded with a higher priority which in turn helps in avoiding some name conflicts. The code of main.py for this method will be:
Python
# importing the sys moduleimport sys        # inserting the mod.py directory at# position 1 in sys.pathsys.path.insert(1, 'D:/projects/base/app/modules')        # importing the module mod.pyimport mod    # calling the function hello() of mod.pymod.hello()
Output:
hello geeks!
We can also import the module by first converting the directory where it exists as python package. To convert a directory to a python package we have to include a file __init__.py in that directory which can be left empty. When we add the file __init__.py we tell python that the directory is a package. After creating the __init__.py the directory tree will look like this:
D :\projects\base
|__main.py 
|__app:
|      |__modules
|          |___mod.py
|          |___init__.py
|__main.py
The way we call for the module in the import statement is we go from the app folder to the mod file and separate each path variable with a ‘.’ . Now for importing mod.py in main.py from this method the code in main.py will be:
Python
# importing the moduleimport app.modules.mod         # calling the hello function of the moduleapp.modules.mod.hello()
Output:
hello geeks!
We can also import a module from an outside directory using the import library. For this, we will first have to import the importlib.util module. Then call the importlib.util.spec_from_file_location() method which takes 2 arguments file_name and file_path, which returns a value. This value will be used with importlib.util.module_from_spec() method to import a module with a specific name. Then we can use this specific name to call the functions, classes, variables of the module.
Python
# importing the importlib.util moduleimport importlib.util        # passing the file name and path as argumentspec = importlib.util.spec_from_file_location(  "mod", "D:/projects/base/app/modules/mod.py")    # importing the module as foofoo = importlib.util.module_from_spec(spec)       spec.loader.exec_module(foo) # calling the hello function of mod.pyfoo.hello()
Output:
hello geeks!
michaelkelem
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python