How to find the common path of a list of paths?

Question:

I have a list with paths that use ‘/’ as delimiter, for example:

aaa/bbb/ccc/ddd
aaa/bbb/ccceee
aaa/bbb/ccc/fff

How can I write a function in python that would return
the string ‘aaa/bbb/’?

Asked By: Carlo Wood

||

Answers:

I am totally new to python (started yesterday), but this is what I came up with:

paths = [ 'aaa/bbb/ccc/ddd/eee', 'aaa/bbb/ccceee/fff', 'aaa/bbb/ddd/eee', 'aaa/bbb/' ]

def get_common_path(paths):
    common = []
    common_size = -1

    for p in paths:
        s = p.split('/')
        s.pop()
        if common_size == -1:
            common_size = len(s)
            common = s
            continue
        while common_size > 0 and s[0:common_size] != common:
            common_size -= 1
            common.pop()

    return '/'.join(common) + '/'

common_path = get_common_path(paths)
print 'Common path = '{}'; length = {}'.format(common_path, len(common_path))

which outputs:

Common path = 'aaa/bbb/'; length = 8
Answered By: Carlo Wood

Newline-separated input like you posted:

paths = """
aaa/bbb/ccc/ddd
aaa/bbb/ccceee
aaa/bbb/ccc/fff
""" 

A cryptic, hacky mix of list comprehension, zip(), set() and join()

common = "".join([y[0] for y in zip(*[x for x in paths.split("n") if any(x)]) if len(set(y)) == 1])
print common[:common.rfind("/")+1]
Answered By: jDo

Commonpath does that for you:

import os

paths = ["aaa/bbb/ccc/ddd",
         "aaa/bbb/ccceee", 
         "aaa/bbb/ccc/fff"]

os.path.commonpath(paths)
Answered By: Vzzarr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.