suggestion for os.path.commonprefix
Cristian Barbarosie
barbaros at lmc.fc.ul.pt
Tue May 21 11:51:22 EDT 2002
One line dissapeared misteriously from the code in my previous posting.
(if number_of_paths == 0) Below is the full version. Sorry for the typo.
One more comment: yes, I suppose dirname could be defined as
def dirname(path): return commonprefix([path])
Cristian Barbarosie
http://www.lmc.fc.ul.pt/~barbaros
-----------------------------------------------------------------
def commonprefix (list_of_paths):
"""Like in os.path, but more in the spirit of path manipulation.
Items must end in os.sep if they represent directories."""
number_of_paths = len(list_of_paths)
if number_of_paths == 0: return ''
first_path = list_of_paths[0]
largest_i = -1
for i in range(len(first_path)):
stop = 0
character = first_path[i]
for n in range(1,number_of_paths):
item = list_of_paths[n]
if (i >= len(item)) or (character <> item[i]):
# here we took advantage of the way Python evaluates
# logical expressions: if the first one is true,
# then the second one is not evaluated
stop = 1
break
if stop: break
if character == os.sep: largest_i = i
prefix = first_path[:largest_i+1]
return prefix
More information about the Python-list
mailing list