简体   繁体   English

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

[英]python Pathlib, how do I remove leading directories to get relative paths?

Let's say I have this directory structure.假设我有这个目录结构。

├── root1
│   └── root2
│       ├── bar
│       │   └── file1
│       ├── foo
│       │   ├── file2
│       │   └── file3
│       └── zoom
│           └── z1
│               └── file41

I want to isolate path components relative to root1/root2 , ie strip out the leading root part, giving relative directories:我想隔离相对于root1/root2路径组件,即root1/root2前导root部分,给出相对目录:

  bar/file1
  foo/file3
  zoom/z1/file41

The root depth can be arbitrary and the files, the node of this tree, can also reside at different levels.根深度可以是任意的,作为这棵树的节点的文件也可以驻留在不同的级别。

This code does it, but I am looking for Pathlib's pythonic way to do it.这段代码做到了,但我正在寻找 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))

You can use relative_to您可以使用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))

Prints印刷

  bar\file1
  foo\file3
  zoom\z1\file41

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM