Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to circumvent the fallacy of Python's os.path.commonprefix?

Tags:

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. Unfortunately, the fact that commonprefix is located in path is rather misleading, since it actually will search for string prefixes.

The question to me is, how can this actually be solved for paths? The issue was briefly mentioned in this (fairly high rated) answer but only as a side-note and the proposed solution (appending slashes to the input of commonprefix) imho has issues, since it will fail for instance for:

os.path.commonprefix(['/usr/var1/log/', '/usr/var2/log/']) # returns /usr/var but it should be /usr 

To prevent others from falling into the same trap, it might be worthwhile to discuss this issue in a separate question: Is there a simple / portable solution for this problem that does not rely on nasty checks on the file system (i.e., access the result of commonprefix and check whether it is a directory and if not returns a os.path.dirname of the result)?

like image 251
bluenote10 Avatar asked Feb 01 '14 14:02

bluenote10


1 Answers

It seems that this issue has been corrected in recent versions of Python. New in version 3.5 is the function os.path.commonpath(), which returns the common path instead of the common string prefix.

like image 176
cjac Avatar answered Oct 17 '22 09:10

cjac