Home > Software engineering >  Cross-platform way to convert filepath to dot notation?
Cross-platform way to convert filepath to dot notation?

Time:11-28

If I have a file path from a module like, e.g. "aaa/bbb/ccc/ddd.py" how would I convert that to "aaa.bbb.ccc.ddd" in python? Also should work with Windows paths, etc. I thought it should be in pathlib, but couldn't find anything.

CodePudding user response:

Also should work with Windows paths, etc. I thought it should be in pathlib, but couldn't find anything.

Assuming that you only have to work with resolved, relative paths (as shown) and that the path encodes the exact package hierarchy that you want:

  • the .with_suffix method can be used to get rid of the .py in a pathlib.Path
  • .parts give you the individual components, which you can then join up.

Thus:

>>> path = pathlib.Path('aaa/bbb/ccc/ddd.py')
>>> '.'.join(path.with_suffix('').parts)
'aaa.bbb.ccc.ddd'
  • Related