You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

nturl2path.py 2.1KB

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