Jeffrey Aylesworth
Jeffrey Aylesworth

Reputation: 8540

Import all the modules in a directory

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

For example, for the directory with:

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

Upvotes: 5

Views: 2857

Answers (1)

Tigran Saluev
Tigran Saluev

Reputation: 3602

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.

Upvotes: 1

Related Questions