Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cross-platform way to convert filepath to dot notation?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading