`path.basename` like function, but to get the root of a path

Question:

os.path has the basename function that returns the last folder/file of the given path, i wonder if there is a easy way to get the root of a path (and why there’s not a function to it in the os.path module)

>>> from os import path
>>> path.basename('./a/b/c')
'c'
>>> """ what if we could do like so:
>>> path.rootname('./a/b/c')
>>> './a'
>>> """

The first thing i though is to make a recursion of path.dirname in the destination till it gets to the root folder but i can’t think a optimal way to do so, tried to play around with .split str method but also couldn’t implement it.

Asked By: Torres

||

Answers:

Maybe the pathlib is here for the rescue?

from pathlib import Path

p = Path("./foo/bar/baz.qwurx")
print(p.parents[len(p.parents)-1])
print(p.parents[len(p.parents)-2])
print(p.parents[len(p.parents)-3])

yields

.
foo
foo/bar

note that ./foo and foo are equal.

Answered By: Cpt.Hook

The solution for the problem (someone pls submit a PEP about this function)

from os import path
from pathlib import Path

def rootname(dest: str):
    """
    Will return the root of a path.
    """
    p = Path(dest)

    return path.join(
        p.parents[len(p.parents) - 1],
        p.parents[len(p.parents) - 2]
    )
Answered By: Torres