Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import all the modules in a directory

Tags:

python

module

Is there any way to import all modules in the current directory, and return a list of them?

For example, for the directory with:

  • mod.py
  • mod2.py
  • mod3.py

It will give you [<module 'mod'>, <module 'mod2'>, <module 'mod3'>]

like image 629
Jeffrey Aylesworth Avatar asked Nov 15 '22 13:11

Jeffrey Aylesworth


1 Answers

I think I've got your idea.

Try the following:

import glob
modules = []
for module_name in glob.glob("*.py"):
    modules.append(__import__(module_name[:-3]))

This way you get a list of module objects and don't pollute the global namespace.

like image 111
Tigran Saluev Avatar answered Dec 18 '22 20:12

Tigran Saluev