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.
-
Googling for python path normalize brings answer in the first link – docs.python.org/library/os.path.htmlPiotr Dobrogost– Piotr Dobrogost2013年12月20日 12:16:48 +00:00Commented Dec 20, 2013 at 12:16
-
@PiotrDobrogost : I dodn't know that it is called path normalization. I had searched for "Python relative path optimization" but the results didn't help.voidMainReturn– voidMainReturn2013年12月20日 19:02:53 +00:00Commented Dec 20, 2013 at 19:02
2 Answers 2
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'
Comments
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'
1 Comment
\\.` or \\?`, which must be preserved unchanged, you can have UNC paths (start with //machine/mountpoint/...) and you can have drive letters (C:/...), and you are not processing ./ elements (current directory). You also want to use path3.replace('\\', '/') to handle either forward or backward slashes the same.