I am dynamically importing files/modules using import_module
. When I had the files in the same directory this worked:
JavaScript
x
3
1
importlib.import_module('child')
2
module.main()
3
However, when I reorganized my folder structure to look this:
JavaScript
1
4
1
- sub
2
- child.py
3
- main.py
4
I assumed that I could do this:
JavaScript
1
3
1
module = importlib.import_module('sub/child')
2
module.main()
3
But it gives me the error
ModuleNotFoundError: No module named ‘child’
I tried the following paths as well:
/sub/child
./sub/child
Advertisement
Answer
import_module()
takes a module name, not a file path, as an argument. This means you must use .
not /
:
JavaScript
1
2
1
module = importlib.import_module('sub.child')
2