Moving one step further @radomaj's answer, here's commonprefix()
-based implementation that produces the correct answer /home
instead of (invalid) /home/tung
for ['/home/tung/abc.txt', '/home/tung123/xyz.txt']
input files:
#!/usr/bin/env python
import os
try:
from pathlib import PurePath
except ImportError: # Python < 3.4
def get_parts(path):
path = os.path.dirname(path) # start with the parent directory
parts = []
previous = None
while path != previous:
previous = path
path, tail = os.path.split(path)
parts.append(tail)
parts.append(path)
parts.reverse()
return parts
else: # pathlib is available
def get_parts(path):
return PurePath(path).parent.parts
def commondir(files):
files_in_parts = list(map(get_parts, files))
return os.path.join(*os.path.commonprefix(files_in_parts))
Example:
print(commondir(['/home/tung/abc.txt', '/home/tung123/xyz.txt']))
# -> /home