Import all modules into a directory

Is there a way to import all the modules into the current directory and return their list?

For example, for a directory with:

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

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

+5
source share
1 answer

I think I have 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 objects moduleand do not pollute the global namespace.

+1
source

All Articles