Search code examples
pythonmoduleglob

Using glob to locate modules and then importing module dynamically


I have several modules I want to import dynamically. The modules are named prefix_? where ? = [0,1,2,3]. I use glob to get a list of the files/modules.

module = glob.glob(prefix_?.py)
module.sort()

Now I want to import one module at a time and run some code.

for m in range(0,len(module),1):
    from module[m] import x, y, z

However I can't do this because module is a list of strings. Is there some way to convert the format from being a string to an actual module that I can import?


Solution

  • You can use importlib module:

    import glob
    import importlib
    module = glob.glob(prefix_?.py)
    module.sort()
    for m in module:      #iterate over list itself, why range?
        mod = importlib.import_module(m[:-3]) #strip off .py