My problem is to find the common path prefix of a given set of files.
Literally I was expecting that \"os.path.commonprefix\" would do just that. Unfortunat
Assuming you want the common directory path, one way is to:
os.path.dirname(filename)
to get its directory path.os.path.abspath( )
to get the path relative to the root. (You might also want to use os.path.realpath( )
to remove symbolic links.)os.path.sep
or os.sep
) to the end of all the normalized directory paths.os.path.dirname( )
on the result of os.path.commonprefix( )
.In code (without removing symbolic links):
def common_path(directories):
norm_paths = [os.path.abspath(p) + os.path.sep for p in directories]
return os.path.dirname(os.path.commonprefix(norm_paths))
def common_path_of_filenames(filenames):
return common_path([os.path.dirname(f) for f in filenames])