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

2019-03-14 18:19发布

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?

2条回答
爷的心禁止访问
2楼-- · 2019-03-14 18:33

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'
查看更多
做自己的国王
3楼-- · 2019-03-14 18:43

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))
查看更多
登录 后发表回答