all Python 3urllib.requestfunction
urllib.request.pathname2url()
paths and URLs
Converts a filesystem path into the path part of a file: URL with percent-encoding: a space becomes %20.
Syntax
urllib.request.pathname2url(path, *, add_scheme=False)
The result is not a full URL: the file: prefix appears only with add_scheme=True (since 3.14), so Path(...).resolve().as_uri() is simpler for a ready address. Since 3.14 an absolute POSIX path gets three slashes: '/tmp/a' → '///tmp/a', where it used to be '/tmp/a' — code that glues 'file://' to the result gives different answers on different versions. On Windows backslashes become forward slashes.
Examples
import urllib.request
print(urllib.request.pathname2url('docs/my file.txt')) # → docs/my%20file.txt
# Python 3.14+
import urllib.request
print(urllib.request.pathname2url('/tmp/a b', add_scheme=True)) # → file:///tmp/a%20b
See also
Open in the full glossarydocs.python.orgReport an inaccuracy