Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two paths with common folder

Tags:

python

Is there a way in python to combine two paths with os.path or any other library which doesn't repeat common subfolders? i.e.

root = '/home/user/test'

rel_path = 'test/files/file.txt'

os.combine(root, rel_path)

And returning /home/user/test/files/file.txt instead /home/user/test/test/files/file.txt

like image 951
lapinkoira Avatar asked Feb 06 '26 08:02

lapinkoira


1 Answers

I think you have to do it manually, I don't think os.path implements this functionality.

Maybe try something like:

def combine_with_duplicate(root, rel_path):
    rs = root.split("/")
    rps = rel_path.split("/")
    popped = False
    for v in rs:
        if v == rps[0]:
            rps.pop(0)
            popped = True
        elif popped:
            break

    return "/".join(rs+rps)


print(combine_with_duplicate('/home/user/test', 'test/files/file.txt'))
# /home/user/test/files/file.txt
print(combine_with_duplicate('/home/user', 'test/files/file.txt'))
# /home/user/test/files/file.txt
print(combine_with_duplicate('/home/user/test', 'user/test/files/file.txt'))
# /home/user/test/files/file.txt
like image 159
DSLima90 Avatar answered Feb 08 '26 21:02

DSLima90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!