Import Module From Subdirectory in Python
-
Import a Module From the Subdirectory in Python Using
__init__.py
-
Import a Module From the Subdirectory in Python Using the
sys.path.insert()
Method
This tutorial will explain the various methods to import a module from the subdirectory in Python. Suppose we have a file in a subdirectory of the project’s directory, and we want to import the file and use its methods in our code.
We can import the file from a subdirectory in Python by declaring the subdirectory as a package. So Python will treat it as a package, and we will be able to import the file for that directory. The other option can be to add the subdirectory to the PYTHONPATH
environment variable, and it is the path where Python looks for the packages to import by default. The details and use of these methods are given below.
Import a Module From the Subdirectory in Python Using __init__.py
The __init__.py
file is used to declare a directory as a package. The __init__.py
file prevents Python from mixing the directory with the same name, so to differentiate between a simple directory and a package, the __init__.py
file is used.
The __init__.py
file can be empty, or it can have the code needed to initialize the package and a list of the modules required to be imported with the package; this list is represented by __all__
variable.
Once the __init__.py
file is added to the subdirectory, we can import the file from the subdirectory like shown in the following example code:
import subdirectory.myfile
Import a Module From the Subdirectory in Python Using the sys.path.insert()
Method
The alternate method to import a file from the subdirectory is to add that directory to the PYTHONPATH
. The PYTHONPATH
is the environment variable that contains the path of the directories that Python searches to import the packages.
Therefore, if we add the subdirectory to the PYTHONPATH
using the sys.path.insert()
method, Python will first look at the directories in PYTHONPATH
and import it from there.
The sys.path.insert()
method will insert the subdirectory to the sys.path
or PYTHONPATH
variable that contains the list of directories that Python will search to import the required module.
The below example code demonstrates how to use the sys.path.insert()
method to import a file from the subdirectory:
import sys
sys.path.insert(0, './subdirectory')
import myfile