Import Module From Subdirectory in Python

  1. Import a Module From the Subdirectory in Python Using __init__.py
  2. Import a File From the Subdirectory in Python by Adding It to PYTHONPATH
  3. Import a File 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 File From the Subdirectory in Python by Adding It to PYTHONPATH

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, Python will first look at the directories in PYTHONPATH and import it from there.

Import a File From the Subdirectory in Python Using the sys.path.insert() Method

We can use the sys.path.insert() method to insert the subdirectory to the sys.path containing the list of directories, including the PYTHONPATH. Python searches the sys.path 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
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Import

  • Import a Variable From Another File in Python