Is there any smart way to combine overlapping paths in python?
Question: Let's say I have two path names: **head** and **tail**. They can overlap with
any number of segments. If they don't I'd like to just join them normally. If
they overlap, I'd like to detect the common part and combine them accordingly.
To be more specific: If there are repetitions in names I'd like to find as
long overlapping part as possible. Example

    
    
    "/root/d1/d2/d1/d2" + "d2/d1/d2/file.txt" == "/root/d1/d2/d1/d2/file.txt"
    and not "/root/d1/d2/d1/d2/d1/d2/file.txt"
    

Is there any ready-to-use library function for such case, or I have to
implement one?


Answer: You can use a list comprehension within `join` function :

    
    
    >>> p1="/root/d1/d2/d1/d2"
    >>> p2="d2/d1/d2/file.txt"
    >>> p1+'/'+'/'.join([i for i in p2.split('/') if i not in p1.split('/')])
    '/root/d1/d2/d1/d2/file.txt'
    

Or if the difference is just the base name of second path you can use
`os.path.basename` to get the bname and concatenate it to `p1` :

    
    
    >>> import os
    >>> p1+'/'+os.path.basename(p2)
    '/root/d1/d2/d1/d2/file.txt'
    

