python路径库,如何删除前导目录以获得相对路径?

2024-04-16 19:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个目录结构

├── 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))

Tags: path目录fooosbarrootfile1file2
1条回答
网友
1楼 · 发布于 2024-04-16 19:14:00

您可以使用relative_to

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

相关问题 更多 >