Reputation: 2705
Say I have the path fodler1/folder2/folder3
, and I don't know in advance the names of the folders.
How can I remove the first part of this path to get only folder2/folder3
?
Upvotes: 1
Views: 3181
Reputation: 812
You can use pathlib.Path
for that:
from pathlib import Path
p = Path("folder1/folder2/folder3")
And either concatenate all parts
except the first:
new_path = Path(*p.parts[1:])
Or create a path relative_to
the first part:
new_path = p.relative_to(p.parts[0])
This code doesn't require specifying the path delimiter, and works for all pathlib
supported platforms (Python >= 3.4).
Upvotes: 4
Reputation: 73450
Use str.split
with 1
as maxsplit
argument:
path = "folder1/folder2/folder3"
path.split("/", 1)[1]
# 'folder2/folder3'
If there is no /
in there, you might be safer with:
path.split("/", 1)[-1] # pick the last of one or two tokens
but that depends on your desired logic in that case.
For better protability across systems, you could replace the slash "/"
with os.path.sep
:
import os
path.split(os.path.sep, 1)[1]
Upvotes: 2