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

前端 未结 5 1355
栀梦
栀梦 2020-12-14 07:52

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 a

5条回答
  •  旧巷少年郎
    2020-12-14 08:16

    The solution from @colton7909 is mostly correct and helped me get to this answer, but has some import errors with Python 3. That and I think this is a better way to deal with the 'file://' part of the URL than simply chopping off the first 7 characters. So I feel this is the most idiomatic way to do this using the standard library:

    import urllib.parse
    url_data = urllib.parse.urlparse('file:///home/user/some%20file.txt')
    path = urllib.parse.unquote(url_data.path)
    

    This example should produce the string '/home/user/some file.txt'

提交回复
热议问题