importing a module when the module name is in a variable

Question:

I have some code like:

data_files = [x[2] for x in os.walk(os.path.dirname(sys.argv[0]))]
hello = data_files[0]
modulename = hello[0].split(".")[0]

import modulename

The goal is to get the name of a file from a directory as a string, pass it to some other code, and then import the module whose name is stored in the variable name.

However, in my code attempt, the modulename in import modulename is treated as the name of the module to import, rather than the string stored in that variable.

How can I get the effect that I want instead?

Asked By: user1801279

||

Answers:

You want the built in __import__ function

new_module = __import__(modulename)
Answered By: mgilson

importlib is probably the way to go. The documentation on it is here. It’s generally preferred over __import__ for most uses.

In your case, you would use:

import importlib
module = importlib.import_module(module_name, package=None)
Answered By: munk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.