home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / NTURL2PATH.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  1.9 KB  |  67 lines

  1. """Convert a NT pathname to a file URL and vice versa."""
  2.  
  3. def url2pathname(url):
  4.     r"""Convert a URL to a DOS path.
  5.  
  6.         ///C|/foo/bar/spam.foo
  7.  
  8.             becomes
  9.  
  10.         C:\foo\bar\spam.foo
  11.     """
  12.     import string, urllib
  13.     if not '|' in url:
  14.         # No drive specifier, just convert slashes
  15.         if url[:4] == '////':
  16.             # path is something like ////host/path/on/remote/host
  17.             # convert this to \\host\path\on\remote\host
  18.             # (notice halving of slashes at the start of the path)
  19.             url = url[2:]
  20.         components = string.split(url, '/')
  21.         # make sure not to convert quoted slashes :-)
  22.         return urllib.unquote(string.join(components, '\\'))
  23.     comp = string.split(url, '|')
  24.     if len(comp) != 2 or comp[0][-1] not in string.letters:
  25.         error = 'Bad URL: ' + url
  26.         raise IOError, error
  27.     drive = string.upper(comp[0][-1])
  28.     components = string.split(comp[1], '/')
  29.     path = drive + ':'
  30.     for  comp in components:
  31.         if comp:
  32.             path = path + '\\' + urllib.unquote(comp)
  33.     return path
  34.  
  35. def pathname2url(p):
  36.     r"""Convert a DOS path name to a file url.
  37.  
  38.         C:\foo\bar\spam.foo
  39.  
  40.             becomes
  41.  
  42.         ///C|/foo/bar/spam.foo
  43.     """
  44.  
  45.     import string, urllib
  46.     if not ':' in p:
  47.         # No drive specifier, just convert slashes and quote the name
  48.         if p[:2] == '\\\\':
  49.             # path is something like \\host\path\on\remote\host
  50.             # convert this to ////host/path/on/remote/host
  51.             # (notice doubling of slashes at the start of the path)
  52.             p = '\\\\' + p
  53.         components = string.split(p, '\\')
  54.         return urllib.quote(string.join(components, '/'))
  55.     comp = string.split(p, ':')
  56.     if len(comp) != 2 or len(comp[0]) > 1:
  57.         error = 'Bad path: ' + p
  58.         raise IOError, error
  59.  
  60.     drive = urllib.quote(string.upper(comp[0]))
  61.     components = string.split(comp[1], '\\')
  62.     path = '///' + drive + '|'
  63.     for comp in components:
  64.         if comp:
  65.             path = path + '/' + urllib.quote(comp)
  66.     return path
  67.