[英]How to get relative path given a parent of unknown location with Python's pathlib?
with pathlib.Path.relative_to
we can get relative paths with:使用
pathlib.Path.relative_to
我们可以获得相对路径:
>>> from pathlib import Path
>>> Path("/path/to/foo/bar/thing").relative_to("/path/to/foo")
PosixPath('bar/thing')
But what if i don't know the exact path of the parent directory (but i do know its name)?但是如果我不知道父目录的确切路径(但我知道它的名字)怎么办?
for example:例如:
Path("/path/to/foo/bar/thing")
relative to "foo"
=> PosixPath('bar/thing')
Path("/path/to/foo/bar/thing")
相对于"foo"
=> PosixPath('bar/thing')
Path("/path/to/foo/bar/thing")
relative to "to"
=> PosixPath('foo/bar/thing')
Path("/path/to/foo/bar/thing")
相对于"to"
=> PosixPath('foo/bar/thing')
Path("/another_path/to/foo/bar/thing")
relative to "foo"
=> PosixPath('bar/thing')
Path("/another_path/to/foo/bar/thing")
相对于"foo"
=> PosixPath('bar/thing')
how do i get a relative path relative to an arbitrary parent directory like this?我如何获得相对于这样的任意父目录的相对路径?
Given鉴于
p = Path("/path/to/foo/bar/thing")
relative_to = 'foo'
do做
relative_p = Path(*p.parts[p.parts.index(relative_to) + 1:])
Essentially, we grab the parts of the path, find the index of relative_to
and slice those parts using that index.本质上,我们抓取路径的各个部分,找到
relative_to
的索引并使用该索引对这些部分进行切片。 Then we pass the sliced parts back to the Path()
constructor to get back our relative path.然后我们将切片的部分传递回
Path()
构造函数以取回我们的相对路径。
Another option另外的选择
import os
relative_p = Path(str(p).split(f'{os.sep}{relative_to}{os.sep}', maxsplit=1)[-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.