user1618465
user1618465

Reputation: 1941

Import module dynamic from a folder python

I have read other post about dynamic import of modules in python. And they work! The problem is when I am importing a module from a specific folder. If I have the main python code and the module in the same folder:

main.py

module.py

If i do:

var = "module"
module = __import__(var)

It works great. But my module is in a specific folder named "modules"

main.py

modules\module.py

If I do:

var = "a"
module = __import__("modules\\"+var)

It doesn't work. I know that I am pretty close of the solution but I can't get it.

Thank you for your help

Upvotes: 3

Views: 3683

Answers (1)

iblazevic
iblazevic

Reputation: 2733

Assuming modules is indeed python package and var is your module name, you separate directory with dot.

var = "module" 
module = __import__("modules.{0}".format(var), globals(), locals(), [], -1)

You can check docs:

import documentation

You to create an __init__.py file in your modules folder.

Upvotes: 3

Related Questions