Skip to content Skip to sidebar Skip to footer

Find A Path In Windows Relative To Another

This problem should be a no-brainer, but I haven't yet been able to nail it. I need a function that takes two parameters, each a file path, relative or absolute, and returns a file

Solution 1:

I agree with you: this seems like a deficiency in os.path.join. Looks like you have to deal with the drives separately. This code passes all your tests:

def findpath(target, start=os.path.curdir):
    sdrive, start = os.path.splitdrive(start)
    tdrive, target = os.path.splitdrive(target)
    rdrive = tdrive or sdrive
    returnos.path.normpath(os.path.join(rdrive, os.path.join(start, target)))

(and yes, I had to nest two os.path.join's to get it to work...)

Post a Comment for "Find A Path In Windows Relative To Another"