将文件路径转换为点符号的跨平台方式?

Cross-platform way to convert filepath to dot notation?

如果我有一个模块的文件路径,例如"aaa/bbb/ccc/ddd.py" 我如何将其转换为 python 中的 "aaa.bbb.ccc.ddd"?还应该使用 Windows 路径等。我认为它应该在 pathlib 中,但找不到任何东西。

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

假设您只需要使用已解析的相对路径(如图所示)并且该路径编码了您想要的确切包层次结构:

  • .with_suffix 方法可用于删除 pathlib.Path
  • 中的 .py
  • .parts 为您提供各个组件,然后您可以将其组合起来。

因此:

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