'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 os.path.commonprefix documentation:
Return the longest path prefix (taken character-by-character)

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

Question 2

if commonprefix is implemented in os.path why isn't it path oriented, meaning return my desired result and not the real one?

Note:

I can implement this easily by myself but if it is already implemented why not using it?



Solution 1:[1]

is there a path oriented function?

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


Split the path into components and call commonprefix() on that e.g.:

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

Solution 2:[2]

Using the pathlib only:

def common_path(path1: Path, path2: Path) -> typing.Optional[Path]:
    while path1 is not None:
        if path2.is_relative_to(path1):
            return path1
        path1 = path1.parent if path1 != path1.parent else None
    return None

Solution 3:[3]

Since Python 3.5, you can use os.path.commonpath, which does exactly what you want. Unlike commonprefix, it works dir-by-dir.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfs
Solution 2 Sergey Kostrukov
Solution 3 Brian McCutchon