如何使用pathlib从当前路径的一部分制作新的Path对象?

Ger*_*Ger 6 python pathlib

我想使用更改Path对象的一部分pathlib

例如,如果您有一个Path对象:

import pathlib
path = pathlib.Path("/home/user/to/some/floder/toto.out")
Run Code Online (Sandbox Code Playgroud)

如何更改文件名?并举例说明获得一条新的道路"/home/user/to/some/folder/other_file.dat"

或更笼统地说,我可以更改该路径的一个或几个元素吗?

我可以得到parts的路径:

In [1]: path.parts
Out[1]: ('/', 'home', 'user', 'to', 'some', 'floder', 'toto.out')
Run Code Online (Sandbox Code Playgroud)

因此,一种解决方法是先连接所需的部分,创建新的字符串,然后创建新的路径,但是我想知道是否有更方便的工具来执行此操作。

编辑

更确切地说,它是否存在与path.name返回路径的补充部分等效的功能:str(path).replace(path.name, "")

Ger*_*Ger 8

为了总结评论,声明如下:

1)为了改变文件名

In [1]: import pathlib

In [2]: path = pathlib.Path("/home/user/to/some/floder/toto.out")

In [3]: path.parent / "other_file.dat"
Out[3]: PosixPath('/home/user/to/some/floder/other_file.dat')
Run Code Online (Sandbox Code Playgroud)

2)为了改变路径的一部分

In [4]: parts = list(path.parts)

In [5]: parts[4] = "other"

In [6]: pathlib.Path(*parts)
Out[6]: PosixPath('/home/user/to/other/floder/toto.out')
Run Code Online (Sandbox Code Playgroud)