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.
>Solution :
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_suffixmethod can be used to get rid of the.pyin apathlib.Path .partsgive 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'