Dynamically loading modules in Python

Have you wanted to load modules, when you didn’t know their name?

I recently came across this problem while refactoring GoogleBot (my IRC bot). I wanted to place loadable modules in a directory, and have them all loaded, without having to know what they are named.

A good fellow called Issac at work helped me with this:

import imp
googlebot_mod_dir = os.path.abspath('modules')
sys.path.append(googlebot_mod_dir)
for module_file in os.listdir(googlebot_mod_dir):
module_name, ext = os.path.splitext(module_file)
if ext == '.py':
module_location = imp.find_module(module_name)
module = imp.load_module(module_name, *module_location)
globals()[module_name] = module

Works like a charm!

Scroll to top