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.
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'
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'
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