Search code examples
python-3.xpathpathlib

How do i remove '/' from the path without using string manipulation and using pathlib


I have a path say path = pathlib.Path('/home/user/dir1/some.txt')

>>> path
PosixPath('/home/user/dir1/some.txt')

How do i get only home/user/dir1 and not the 1st '/' ?

If i use path.parent it will give me

>>> path.parent
PosixPath('/home/user/dir1')

How do i eliminate the 1st '/' from the path ?

I don't want to do any string manipulation like lstrip('/') Is there any way to do this using pathlib.Path ?

Thanks in advance...!


Solution

  • you could use relative_to:

    from pathlib import Path
    
    some_path = Path("/home/user/dir1/some.txt")
    print(some_path.relative_to("/"))
    

    or

    root = Path("/")
    print(some_path.relative_to(root))
    

    or even

    print(some_path.relative_to(some_path.root))
    

    all of these return PosixPath('home/user/dir1/some.txt') (and print home/user/dir1/some.txt).