posixpath normpath with duplicate leading /

Nathan K. Pemberton nate.pemberton at lmco.com
Thu Aug 26 21:47:48 EDT 1999


I am running Python 1.5.2 on HP-UX 9.0. The posixpath function
'normpath' seems to handle multiple leading slashes incorrectly. This is
cosmetic, not a functional problem since the file system and/or shell
collapses multiple slashes anyway.

The issue: multiple slashes should always collapse to a single slash,
even as the leading component. This is true on Unix; I'm not sure
whether this would impact DOS.

e.g. how it currently works:
>>> os.path.normpath('////users/nathanp//tmp/.')
'////users/nathanp/tmp'

how it should work:
'/users/nathanp/tmp'

Here is a proposed implementation which seems to work:


# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
# It should be understood that this may change the meaning of the path
# if it contains symbolic links!

def normpath(path):
 """Normalize path, eliminating double slashes, etc."""
 import string
 # Treat initial slashes specially
 slashes = ''
 if path[:1] == '/':
  slashes = '/'
 comps = string.splitfields(path, '/')
 i = 0
 while i < len(comps):
  if comps[i] == '.':
   del comps[i]
   while i < len(comps) and comps[i] == '':
    del comps[i]
  elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
   del comps[i-1:i+1]
   i = i-1
  elif comps[i] == '':
   if i == 0 or ( i > 0 and comps[i-1] <> ''):
    del comps[i]
  else:
   i = i+1
 # If the path is now empty, substitute '.'
 if not comps and not slashes:
  comps.append('.')
 return slashes + string.joinfields(comps, '/')







More information about the Python-list mailing list