Python os.path.commonprefix - is there a path-oriented function?

So, I have this python code:

print os.path.commonprefix([r'C:\root\dir',r'C:\root\dir1']) 

Real result

 C:\root\dir 

Desired Result

 C:\root 

Question 1

Based on the os.path.commonprefix documentation:
Return the longest path prefix (taken for each character)

Is there a similar function that:
Return the longest path prefix ( taken dir directory )

Question 2

If commonprefix implemented in os.path , why is it os.path , that is, it returns my desired result, and not real?

Note:

I can implement this easily myself, but if it is already implemented, why not use it?

+2
source share
1 answer

is there a path-oriented function?

no and yes. commonprefix() can work with arbitrary sequences, not just strings.


Divide the path into components and call commonprefix() on this, for example:

 >>> import os >>> from pathlib import PureWindowsPath >>> a, b = map(PureWindowsPath, [r'C:\root\dir', r'C:\root\dir1']) >>> PureWindowsPath(*os.path.commonprefix([a.parts, b.parts])) PureWindowsPath('C:/root') 
+3
source

All Articles