Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert module path to import_module name format

Is there a built-in or simple way to convert a file path (module path) to a name argument to be used by the importlib.import_module function?

For example:

'path/module.py' -> 'path.module'

I could do something like this:

if path.endswith('.py'):
    path = path[:-3]

path = path.replace('/', '.')

But I was looking for a simpler way.

like image 982
KelvinS Avatar asked Jan 21 '26 08:01

KelvinS


1 Answers

Would:

path.split('.py')[0].replace("/", ".")

be suitable?

like image 143
BpY Avatar answered Jan 23 '26 00:01

BpY