I am trying to import the modules dynamically using python. My directory structure is
root_folder1:
-sub_folder1
-sub_folder2
---sub_sub_folder
-my_file1.py
-my_file2.py
-my_main_file.py
I have to import my_file1.py and my_file2.py(which is inside sub_Sub_folder) methods into my_main_file.py(inside the root_folder1). I am running my_main_file.py in the root_folder only.
To dynamically import those two file I tried using importlib and import. But I got an error 'no module named "
My code in my_main_file.py is:
import os, fnmatch
from pathlib import Path
import importlib
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
listoffiles = os.listdir("sub_folder2/sub_sub_folder/")
pattern = "*.py"
abs_path = "sub_folder2/sub_sub_folder/"
for entry in listoffiles:
if fnmatch.fnmatch(entry, pattern):
print(entry,abs_path)
try:
spec = importlib.util.spec_from_file_location(entry, abs_path)
print(spec)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
print(f'fp:{foo}{spec}')
except Exception as e:
print(f'The error is {e}')
i tried using the importlib.import_module(entry,package=abs_path). I got an error.
When I run the above code I am getting "The error is 'NoneType' object has no attribute 'loader'".
My question is: How do I dynmaically import the files my_file1.py,my_file2.py into my_main_file.py and uses the fucntions of my_file1 and my_file2.
I tried Import arbitrary python source file. (Python 3.3+) and I am getting no module error