Created
January 26, 2017 07:01
-
-
Save chrono-meter/7e47528a3f902c9ade7e0cc442394d08 to your computer and use it in GitHub Desktop.
Python: Common prefix of pathlib.Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
import pathlib | |
def common_prefix(*paths): | |
"""Common prefix of given paths""" | |
counter = collections.Counter() | |
for path in paths: | |
assert isinstance(path, pathlib.Path) | |
counter.update([path]) | |
counter.update(path.parents) | |
try: | |
return sorted((x for x, count in counter.items() if count >= len(paths)), key=lambda x: len(str(x)))[-1] | |
except LookupError as e: | |
raise ValueError('No common prefix found') from e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment