3

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.

KelvinS
  • 2,870
  • 8
  • 34
  • 67

1 Answers1

1

Would:

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

be suitable?

BpY
  • 403
  • 5
  • 12
  • This example is more concise and will probably do the job, but I was looking for a built-in function that does it and that will probably deal with corner cases (maybe related to the os). Anyway, if there is no such thing, this answer will help, thanks. – KelvinS Dec 27 '19 at 14:09
  • does [this](https://stackoverflow.com/questions/14360389/getting-file-path-from-command-line-argument-in-python/47324233) or [this](https://stackoverflow.com/questions/52593420/python-convert-windows-file-path-in-a-variable) help? – BpY Dec 27 '19 at 14:11