3

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I haves this error: SyntaxError: Non-ASCII character '\xe1' in file C:\modules\_init_.py on line 2, but no encoding declared; see python.org/peps/pep-0263.html for details
I edited a question a little bit to be accurate with import. And about your error, really don't know what's inside your init.py. Try deleting everything and leave it empty.
I had to create init.py file in the modules folder and it works! Just create init.py empty. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.