suggestion for os.path.commonprefix

Cristian Barbarosie barbaros at lmc.fc.ul.pt
Tue May 21 05:45:49 EDT 2002


I noticed the following peculiar behaviour os.path.commonprefix:

>>> os.path.commonprefix(['/home/someuser/modulef/essay.tex',
... '/home/someuser/mollifiers/fig01.ps'])
'/home/someuser/mo'

  I think the answer should be '/home/someuser/'. At least, this is
what I expect when I do pathname manipulations in Python.
  So I propose the following replacement for os.path.commonprefix:

-------------------------------------------------------------------
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)
   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
--------------------------------------------------------------------

Notes:

1. I know that "if number_of_paths == 0" is the same as "if not
number_of_paths", but I prefer the first version, it is more readable.

2. It is important that directory names end in os.sep. This means that
you cannot use os.path.dirname, as it returns something not ending in
os.sep:
>>> os.path.dirname('/home/someuser/modulef/essay.tex')
'/home/someuser/modulef'
So I built my own dirname:

def dirname (path):
  """The inconvenient of os.path.dirname is that it does not give
  a name ending in / (that is, ending in os.sep),
  except when it returns root directory."""
  dir = os.path.dirname (path)
  l = len(dir)
  if l==0: return ''
  if dir[l-1] != os.sep:
    dir = dir + os.sep
  return dir

3. The problem with my version of commonprefix is that, if you give
just the name of a _file_ as an argument, it returns the parent
directory instead of the file itself:
>>> commonprefix(['/home/someuser/modulef/essay.tex'])
'/home/someuser/modulef/'
For me this behaviour is acceptable, for others it may be not.

Thank you for your attention,
Cristian Barbarosie
barbaros at lmc.fc.ul.pt
http://www.lmc.fc.ul.pt/~barbaros



More information about the Python-list mailing list