phyce
phyce

Reputation: 65

Dynamic module loading using __import__

I want to make a function that loads all the .py files in a directory, and imports them using

__import__(), but I keep getting an ImportError: No module named toolboxtool1.

This is file structure:

project/dirreader.py
project/tools/toolboxtool1.py
project/tools/toolboxtool2.py
project/tools/toolboxtool3.py

What am I doing wrong?

import os
os.chdir(os.getcwd()+"/tools/")
stuff = os.listdir(os.getcwd())
for i in range(0,len(stuff)):
    if stuff[i][-3:] == ".py":
        stuff[i] = stuff[i][:-3]
    else:
        pass
modules = map(__import__, stuff)

Upvotes: 0

Views: 223

Answers (1)

warvariuc
warvariuc

Reputation: 59674

Try prefixing the module names with "tools."

stuff[i] = 'tools.' + stuff[i][:-3]

because the modules you are trying to import are inside tools module package.

Upvotes: 1

Related Questions