Python 的 pathlib 获取父级的相对路径 [英] Python's pathlib get parent's relative path
问题描述
考虑以下Path
:
导入路径库path = pathlib.Path(r'C:\users\user1\documents\importantdocuments')
如何从 Path
中提取准确的字符串 documents\importantdocuments
?
我知道这个例子看起来很傻,这里的实际上下文是将本地文件转换为远程下载链接.
使用 PurePath.relative_to()
方法生成相对路径.
您不太清楚基本路径是如何确定的;这里有两个选项:
secondparent = path.parent.parenthomedir = pathlib.Path(r'C:\users\user1')
然后只需在 path.relative_to(secondparent)
或 path.relative_to(homedir)
结果上使用 str()
.
演示:
<预><代码>>>>导入路径库>>>path = pathlib.Path(r'C:\users\user1\documents\importantdocuments')>>>secondparent = path.parent.parent>>>homedir = pathlib.Path(r'C:\users\user1')>>>str(path.relative_to(secondparent))'文件\\重要文件'>>>str(path.relative_to(homedir))'文件\\重要文件'Consider the following Path
:
import pathlib
path = pathlib.Path(r'C:\users\user1\documents\importantdocuments')
How can I extract the exact string documents\importantdocuments
from that Path
?
I know this example looks silly, the real context here is translating a local file to a remote download link.
Use the PurePath.relative_to()
method to produce a relative path.
You weren't very clear as to how the base path is determined; here are two options:
secondparent = path.parent.parent
homedir = pathlib.Path(r'C:\users\user1')
then just use str()
on the path.relative_to(secondparent)
or path.relative_to(homedir)
result.
Demo:
>>> import pathlib
>>> path = pathlib.Path(r'C:\users\user1\documents\importantdocuments')
>>> secondparent = path.parent.parent
>>> homedir = pathlib.Path(r'C:\users\user1')
>>> str(path.relative_to(secondparent))
'documents\\importantdocuments'
>>> str(path.relative_to(homedir))
'documents\\importantdocuments'
这篇关于Python 的 pathlib 获取父级的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!