0

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

vaanumalar
  • 57
  • 1
  • 11
  • you can do import sub_folder_2.sub_sub_folder.my_file1 in python3 – sinback Apr 08 '21 at 13:10
  • I wanted to do dynamically. – vaanumalar Apr 08 '21 at 13:20
  • I think see what you are doing wrong now. `importlib.util.spec_from_file_location` expects the path (second argument) to lead to the .py file you're trying to import, so you want something like `importlib.util.spec_from_file_location(entry.strip('.py'), abs_path + entry)` – sinback Apr 08 '21 at 13:37
  • Hi sinback, Thanks after adding abs_path+entry the answer I am getting here is ModuleSpec(name='filename', loader=<_frozen_importlib_external.SourceFileLo ader object at 0x01DC6DB0>, origin='../../6bc61c4637e2_.py') . But the next two lines are not getting executed foo= importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) , I hope module can be imported if I dont gett any error in these two lines. am I correct? – vaanumalar Apr 12 '21 at 09:17

0 Answers0