Convert a filename to a file:// URL Convert a filename to a file:// URL python python

Convert a filename to a file:// URL


For completeness, in Python 3.4+, you should do:

import pathlibpathlib.Path(absolute_path_string).as_uri()


I'm not sure the docs are rigorous enough to guarantee it, but I think this works in practice:

import urlparse, urllibdef path2url(path):    return urlparse.urljoin(      'file:', urllib.pathname2url(path))


Credit to comment from @danodonovan above.

For Python3, the following code will work:

from urllib.parse import urljoinfrom urllib.request import pathname2urldef path2url(path):    return urljoin('file:', pathname2url(path))