假设我有以下目录结构。
├── root1
│ └── root2
│ ├── bar
│ │ └── file1
│ ├── foo
│ │ ├── file2
│ │ └── file3
│ └── zoom
│ └── z1
│ └── file41
我想要隔离相对于
root1/root2
的路径组件,即去除前导的root
部分,给出相对目录: bar/file1
foo/file3
zoom/z1/file41
根节点的深度可以任意设置,而文件作为这个树形结构的节点可以位于不同的层次上。
以下代码实现了此功能,但我想找到 Pathlib 的 Pythonic 方法来完成它。
from pathlib import Path
import os
#these would come from os.walk or some glob...
file1 = Path("root1/root2/bar/file1")
file2 = Path("root1/root2/foo/file3")
file41 = Path("root1/root2/zoom/z1/file41")
root = Path("root1/root2")
#take out the root prefix by string replacement.
for file_ in [file1, file2, file41]:
#is there a PathLib way to do this?
file_relative = Path(str(file_).replace(str(root),"").lstrip(os.path.sep))
print(" %s" % (file_relative))
file_.relative_to(root)
是你要找的吗? - hurlenkorelative_to
也不会有太大的影响。 - JL Peyret