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.
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()
The imp module (suggested in the accepted answer) has been deprecated since version 3.4 in favor of importlib.
Instead of using imp.load_source
, you can now use importlib.machinery.SourceFileLoader.load_module
:
import os
from importlib.machinery import SourceFileLoader
module_path = os.path.join('root_dir', 'parent_dir', 'my_module.py')
# Load your module using the module's path
my_module = SourceFileLoader('my_module', module_path).load_module()
# Now you can access the module's functions by using the dot operator
my_module.my_function()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With