pythonimportdirectoryoperating-systemsys

How to import using a path that is a variable in Python


I am trying to make a program that will go through and visit an array of directories and run a program and create a file inside.

I have everything working except that I need to figure out a way to import from a new path each time to get to a new directory.

For example:

L =["directory1", "directory2", "directory3"]
for i in range(len(L)):
   #I know this is wrong, but just to give an idea
   myPath = "parent."+L[i]
   from myPath import file
   #make file... etc.

Obviously when I use myPath as a variable for the path to import, I get an error. I have tried several different ways by searching online through Stack Overflow and reading OS and Sys documentation, but have come to no working result.


Solution

  • You can use 'imp' module to load source code of python scrips

    import imp
    root_dir = '/root/'
    dirs =["directory1", "directory2", "directory3"]
    
    for _dir in dirs:
        module_path = os.path.join(root_dir,_dir,'module.py')
    
        mod = imp.load_source("module_name", module_path)
    
        # now you can call function in regular way, like mod.some_func()