How to remove the first part of a path?

Question:

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?

Asked By: YoavKlein

||

Answers:

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]
Answered By: user2390182

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).

Answered By: user107511
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.