Hi,
I'm trying to import dynamically import python files in a directory.
For example if the directory is:
utility
------init.py
------file1.py
------file2.py
------file3.py
The code to import them would be
from utility import file1
from utility import file2
from utility import file3
I want this line of code to be executed dynamically. So if I add a file4.py
, I don't want to write from utility import import file4
. That's why I want them to import dynamically.
However, my code below gives an error of ImportError: cannot import name 'filename'
where it treats the filename as an actual string and not as a variable.
Is there a way around this?
Here is the current code:
import utility
for f in files:
if f.endswith(".py") and not f.startswith('__init__'):
filename = f.split('.')
from utility import filename[0]
P.S. There are some solutions in the stack overflow like this one:
https://stackoverflow.com/questions/1057431/how-to-load-all-modules-in-a-folder
But again, it requires to be executed every time I add a python file in the directory (i.e. no dynamic)