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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With