Python Pathlib,如何移除前导目录以获取相对路径?

5

假设我有以下目录结构。

├── 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) 是你要找的吗? - hurlenko
是的,我也刚发现了。如果你加进去,我会接受它的。 - JL Peyret
@hurlenko如果您还没有开始,我可能会删除这个问题,因为它似乎是一个重复的问题。 - JL Peyret
好的,你决定。 - hurlenko
你写了这个内容,所以我会接受。我查找了相关的问题,但没有显示出来,因此再提一下relative_to也不会有太大的影响。 - JL Peyret
1个回答

13

简而言之:使用 Path.relative_to 方法:

Path("a/b/c").relative_to("a/b")  # returns PosixPath('c')

完整示例:

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 = file_.relative_to(root)
    print("  %s" % (file_relative))

打印

  bar\file1
  foo\file3
  zoom\z1\file41

太好了!我也发现os.path.relpath可以做类似的事情。 - rlf89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接