如何组合多个 pathlib 对象?
How do you combine more than one pathlib object?
我有两个使用 Python 的路径库的 Path 对象,pathA = Path('/source/parent')
和 pathB = Path('/child/grandchild')
。将两者结合起来以获得 Path('/source/parent/child/grandchild')
对象的最直接方法是什么?
根据 docs:
您可以通过 pathlib.PurePath(*pathsegments)
轻松完成此操作
"Each element of pathsegments can be either a string representing a
path segment, an object implementing the os.PathLike interface which
returns a string, or another path object."
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')
所以对你来说是:
pathA = pathlib.Path('source/parent')
pathB = pathlib.Path('child/grandchild')
pathAB = pathlib.PurePath(pathA, pathB)
Output: source/parent/child/grandchild
备注
"When several absolute paths are given, the last is taken as an anchor
(mimicking os.path.join()’s behaviour):"
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
即使你这样做:
pathA = pathlib.Path('/source/parent')
pathB = pathlib.Path('/child/grandchild')
pathAB = pathlib.PurePath(pathA, pathB)
Pathlib 将像处理由字符串表示的路径对象一样处理 pathB。
Output: source/child/grandchild
我有两个使用 Python 的路径库的 Path 对象,pathA = Path('/source/parent')
和 pathB = Path('/child/grandchild')
。将两者结合起来以获得 Path('/source/parent/child/grandchild')
对象的最直接方法是什么?
根据 docs:
您可以通过 pathlib.PurePath(*pathsegments)
"Each element of pathsegments can be either a string representing a path segment, an object implementing the os.PathLike interface which returns a string, or another path object."
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')
所以对你来说是:
pathA = pathlib.Path('source/parent')
pathB = pathlib.Path('child/grandchild')
pathAB = pathlib.PurePath(pathA, pathB)
Output: source/parent/child/grandchild
备注
"When several absolute paths are given, the last is taken as an anchor (mimicking os.path.join()’s behaviour):"
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
即使你这样做:
pathA = pathlib.Path('/source/parent')
pathB = pathlib.Path('/child/grandchild')
pathAB = pathlib.PurePath(pathA, pathB)
Pathlib 将像处理由字符串表示的路径对象一样处理 pathB。
Output: source/child/grandchild