如何为Python路径库添加前缀?路径与另一条路径?



我有一个pathlib.Path('/etc')。如果我需要用pathlib.Path('/mnt/chroot')作为前缀,然后像这样做:

Path('/mnt/chroot') / Path('/etc')

我只是以:PosixPath('/etc')结束,大概是因为Path都是绝对路径,不能连接。

我可以像这样拼凑出一个解决方案:

Path('/mnt/chroot') / str(Path('/etc')).removeprefix('/')

但这太啰嗦了,而且很粗俗。有没有更简单、更合适的方法来做这件事?

您可以使用relative_to方法将Path('/etc')转换为相对路径:

Path('/mnt/chroot') / Path('/etc').relative_to('/')

我只是想用一个跨平台的解决方案来扩展Kyle的答案。它动态地获取文件系统的根目录。

root = os.path.abspath(".").split(os.path.sep)[0] + os.path.sep
path = Path("/mnt/chroot") / Path("/etc").relative_to(root)

不知道这是否增加了什么,但这就是。

最新更新