Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import module dynamic from a folder python

Tags:

python

import

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

like image 598
user1618465 Avatar asked Aug 08 '26 08:08

user1618465


1 Answers

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.

like image 143
iblazevic Avatar answered Aug 10 '26 00:08

iblazevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!