Directory structure looks like this:
moduleImportTest
|____ main.py
|____ test
|___ mymod.py
I am trying to use importlib to import mymod.py from main.py. At the moment, main.py looks like this:
import importlib, os
theFile = os.path.dirname(os.path.abspath(__file__)) + "/test/mymod.py"
print(theFile)
importlib.import_module(theFile)
The print statement on line 3 outputs the correct file path (though I've swapped my real name for "username" in this example:)
/home/username/moduleImportTest/test/mymod.py
However, line 4 throws an exception:
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named '/home/username/moduleImportTest/test/mymod'
I can't work out what's causing this. I'm really at a loss for what to try.
Much of the online information about this suggests that rather than passing a path directly to importlib, I should first add the relevant directory to the path using sys and then use a regular import statement to import the module normally. The reason I don't want to take this approach is that in the future I want to be able to iterate through a particular directory and import all modules in there, regardless of name.
Any idea how I can resolve this? I'm open to trying something completely different to what I'm doing, but only if it maintains the ability to iterate and import all as described above.