Is there a convenient way to map a file uri to os.

2019-03-14 18:42发布

问题:

A subsystem which I have no control over insists on providing filesystem paths in the form of a uri. Is there a python module/function which can convert this path into the appropriate form expected by the filesystem in a platform independent manner?

回答1:

The urlparse module provides the path from the URI:

import os, urlparse
p = urlparse.urlparse('file://C:/test/doc.txt')
finalPath = os.path.abspath(os.path.join(p.netloc, p.path))


回答2:

For future readers. The solution from @Jakob Bowyer doesn't convert URL characters to ascii. After a bit of digging I found this solution:

>>> import urllib, urlparse
>>> urllib.url2pathname(urlparse.urlparse('file:///home/user/some%20file.txt').path)
'/home/user/some file.txt'

EDIT:

Here's what I ended up using:

>>> import urllib
>>> urllib.unquote('file:///home/user/some%20file.txt')[7:]
'/home/user/some file.txt'