Get Off My Lawn
Get Off My Lawn

Reputation: 36309

How to import dynamic module within a sub directory

I am dynamically importing files/modules using import_module. When I had the files in the same directory this worked:

importlib.import_module('child')
module.main()

However, when I reorganized my folder structure to look this:

- sub
  - child.py
- main.py

I assumed that I could do this:

module = importlib.import_module('sub/child')
module.main()

But it gives me the error

ModuleNotFoundError: No module named 'child'

I tried the following paths as well:

Upvotes: 0

Views: 278

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83527

import_module() takes a module name, not a file path, as an argument. This means you must use . not /:

module = importlib.import_module('sub.child')

Upvotes: 1

Related Questions