nturl2path.py 2.19 KB
Newer Older
1
"""Convert a NT pathname to a file URL and vice versa."""
Guido van Rossum's avatar
Guido van Rossum committed
2 3

def url2pathname(url):
4 5 6 7 8 9
    """OS-specific conversion from a relative URL of the 'file' scheme
    to a file system path; not recommended for general use."""
    # e.g.
    # ///C|/foo/bar/spam.foo
    # becomes
    # C:\foo\bar\spam.foo
Tim Peters's avatar
Tim Peters committed
10
    import string, urllib
11 12
    # Windows itself uses ":" even in URLs.
    url = url.replace(':', '|')
Tim Peters's avatar
Tim Peters committed
13 14 15 16 17 18 19
    if not '|' in url:
        # No drive specifier, just convert slashes
        if url[:4] == '////':
            # path is something like ////host/path/on/remote/host
            # convert this to \\host\path\on\remote\host
            # (notice halving of slashes at the start of the path)
            url = url[2:]
20
        components = url.split('/')
Tim Peters's avatar
Tim Peters committed
21
        # make sure not to convert quoted slashes :-)
22 23
        return urllib.unquote('\\'.join(components))
    comp = url.split('|')
24
    if len(comp) != 2 or comp[0][-1] not in string.ascii_letters:
Tim Peters's avatar
Tim Peters committed
25 26
        error = 'Bad URL: ' + url
        raise IOError, error
27 28
    drive = comp[0][-1].upper()
    components = comp[1].split('/')
Tim Peters's avatar
Tim Peters committed
29 30 31 32 33
    path = drive + ':'
    for  comp in components:
        if comp:
            path = path + '\\' + urllib.unquote(comp)
    return path
Guido van Rossum's avatar
Guido van Rossum committed
34 35

def pathname2url(p):
36 37 38 39 40 41
    """OS-specific conversion from a file system path to a relative URL
    of the 'file' scheme; not recommended for general use."""
    # e.g.
    # C:\foo\bar\spam.foo
    # becomes
    # ///C|/foo/bar/spam.foo
42
    import urllib
Tim Peters's avatar
Tim Peters committed
43 44 45 46 47 48 49
    if not ':' in p:
        # No drive specifier, just convert slashes and quote the name
        if p[:2] == '\\\\':
        # path is something like \\host\path\on\remote\host
        # convert this to ////host/path/on/remote/host
        # (notice doubling of slashes at the start of the path)
            p = '\\\\' + p
50 51 52
        components = p.split('\\')
        return urllib.quote('/'.join(components))
    comp = p.split(':')
Tim Peters's avatar
Tim Peters committed
53 54 55
    if len(comp) != 2 or len(comp[0]) > 1:
        error = 'Bad path: ' + p
        raise IOError, error
Guido van Rossum's avatar
Guido van Rossum committed
56

57 58
    drive = urllib.quote(comp[0].upper())
    components = comp[1].split('\\')
59
    path = '///' + drive + ':'
Tim Peters's avatar
Tim Peters committed
60 61 62 63
    for comp in components:
        if comp:
            path = path + '/' + urllib.quote(comp)
    return path