Python Import All Modules in One Directory

Python Import All Modules in One Directory

There is a need to import modules into the Python framework to extend the capabilities of the language and work with several libraries and modules.

Importing modules one at a time can become a hassle and might waste significant amounts of time. This tutorial discusses how to import all the modules present in a directory in Python.

To explain this further, let us take an example directory containing different modules that need to be imported. The structure of the directory would look like this:

/a
	x.py
	y.py
	z.py

Import All Modules Present in One Directory in Python

The first step would be to create a new python file in the given directory, the name of this file being __init__.py.

This file would have the following contents:

import x
import y
import z

The programmer has to utilize the list dir and list all the py files. These files can be imported with the following code:

import os
for module in os.listdir(os.path.dirname(__file__)):
    if module == '__init__.py' or module[-3:] != '.py':
        continue
    __import__(module[:-3], locals(), globals())
del module

The modules can now be added by simply going to your code and writing this:

import a

These modules can now be further accessed with the help of this:

a.x
a.y
a.z

In newer versions of Python, we can make some tweaks and utilize the new importlib module. However, this module comes up with a lot of hassles.

Related Article - Python Import

  • Python Circular Import
  • Import All Functions From File in Python
  • Import a Variable From Another File in Python
  • Import a Module From a Full File Path in Python
  • Import Modules From Parent Directory in Python
  • Related Article - Python Module

  • Import Files in Python
  • Type Hints in Python
  • The fnmatch Module in Python
  • The Telnetlib Module in Python
  • Socket Programming in Python: A Beginners Guide