Let’s say I have this directory structure.
JavaScript
x
12
12
1
├── root1
2
│ └── root2
3
│ ├── bar
4
│ │ └── file1
5
│ ├── foo
6
│ │ ├── file2
7
│ │ └── file3
8
│ └── zoom
9
│ └── z1
10
│ └── file41
11
12
I want to isolate path components relative to root1/root2
, i.e. strip out the leading root
part, giving relative directories:
JavaScript
1
4
1
bar/file1
2
foo/file3
3
zoom/z1/file41
4
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.
JavaScript
1
17
17
1
from pathlib import Path
2
import os
3
4
#these would come from os.walk or some glob...
5
file1 = Path("root1/root2/bar/file1")
6
file2 = Path("root1/root2/foo/file3")
7
file41 = Path("root1/root2/zoom/z1/file41")
8
9
root = Path("root1/root2")
10
11
#take out the root prefix by string replacement.
12
for file_ in [file1, file2, file41]:
13
14
#is there a PathLib way to do this?🤔
15
file_relative = Path(str(file_).replace(str(root),"").lstrip(os.path.sep))
16
print(" %s" % (file_relative))
17
Advertisement
Answer
TLDR: use Path.relative_to:
JavaScript
1
2
1
Path("a/b/c").relative_to("a/b") # returns PosixPath('c')
2
Full example:
JavaScript
1
18
18
1
from pathlib import Path
2
import os
3
4
# these would come from os.walk or some glob...
5
file1 = Path("root1/root2/bar/file1")
6
file2 = Path("root1/root2/foo/file3")
7
file41 = Path("root1/root2/zoom/z1/file41")
8
9
root = Path("root1/root2")
10
11
# take out the root prefix by string replacement.
12
for file_ in [file1, file2, file41]:
13
14
# is there a PathLib way to do this?🤔
15
file_relative = file_.relative_to(root)
16
print(" %s" % (file_relative))
17
18
Prints
JavaScript
1
4
1
barfile1
2
foofile3
3
zoomz1file41
4