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
P.S. There are some solutions in the stack overflow like this one:
But again, it requires to be executed every time I add a python file in the directory (i.e. no dynamic)