Skip to content

Instantly share code, notes, and snippets.

@chrono-meter
Created January 26, 2017 07:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrono-meter/7e47528a3f902c9ade7e0cc442394d08 to your computer and use it in GitHub Desktop.
Save chrono-meter/7e47528a3f902c9ade7e0cc442394d08 to your computer and use it in GitHub Desktop.
Python: Common prefix of pathlib.Path
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