5

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'>]

Jeffrey Aylesworth
  • 8,242
  • 9
  • 40
  • 57
  • possible duplicate of [Loading all modules in a folder in Python](http://stackoverflow.com/questions/1057431/loading-all-modules-in-a-folder-in-python) – Michael Mrozek Mar 25 '12 at 06:13

1 Answers1

1

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.

Tigran Saluev
  • 3,351
  • 2
  • 26
  • 40