Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python relative path simplifier

I am having issues with paths, hitting the Windows' restriction on the number of characters in the path at 256.

In some place in my python script the 2 paths are getting appended and they both are relative paths, and these become very long:

e.g.:

path1 = "..\\..\\..\\..\\..\\..\\..\\Source/lib/Target/abcd/abc_def_ghf/source/zzzModule/"
path2 = "../../../../../../../../Source/directory/Common/headerFile.h"

Appended path:

path3 = "..\\..\\..\\..\\..\\..\\..\\Source/lib/Target/abcd/abc_def_ghf/source/zzzModule/../../../../../../../../Source/directory/Common/headerFile.h"

And path3 is passed in my Visual Studio solution. At this point VS stops and says that the file is not found.

The observation here is that the final path3 goes 7 levels up then 7 levels down and then again 8 levels up. Is there any utility in python which will take this and generate a simplified relative path for me?

e.g.

some_utility(path3) = "../../../../../../../../Source/directory/Common/headerFile.h"

I know I can write a utility myself but I am just checking if there is any. If there is some it will save my 20 minutes of coding.

like image 407
voidMainReturn Avatar asked Sep 03 '25 13:09

voidMainReturn


2 Answers

Use os.path.normpath to resolve .. in the path:

In [93]: os.path.normpath(os.path.join(path1,path2))
Out[93]: '../Source/directory/Common/headerFile.h'
like image 121
unutbu Avatar answered Sep 05 '25 03:09

unutbu


I would use os.path.normpath (+1 @unutbu), but just for fun, here's a way to do it manually:

def normpath(path3):
    path = path3.split('/')  # or use os.path.sep
    answer = []
    for p in path:
        if p != '..':
            answer.append(p)
        else:
            if all(a=='..' for a in answer):
                answer.append(p)
            else:
                answer.pop()
    return '/'.join(answer)

And the output:

In [41]: normpath("../../../../../../../Source/lib/Target/abcd/abc_def_ghf/source/zzzModule/../../../../../../../../Source/directory/Common/headerFile.h")
Out[41]: '../../../../../../../../Source/directory/Common/headerFile.h'
like image 28
inspectorG4dget Avatar answered Sep 05 '25 02:09

inspectorG4dget