Convert a filename to a file:// URL

前端 未结 4 1616
眼角桃花
眼角桃花 2020-12-05 06:46

In WeasyPrint’s public API I accept filenames (among other types) for the HTML inputs. Any filename that works with the built-in open() should work, but I need

相关标签:
4条回答
  • 2020-12-05 07:04

    Does the following work for you?

    from urlparse import urlparse, urlunparse
    
    urlunparse(urlparse('yourURL')._replace(scheme='file'))
    
    0 讨论(0)
  • 2020-12-05 07:21

    Credit to comment from @danodonovan above.

    For Python3, the following code will work:

    from urllib.parse import urljoin
    from urllib.request import pathname2url
    
    def path2url(path):
        return urljoin('file:', pathname2url(path))
    
    0 讨论(0)
  • 2020-12-05 07:23

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

    import pathlib
    
    pathlib.Path(absolute_path_string).as_uri()
    
    0 讨论(0)
  • 2020-12-05 07:27

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

    import urlparse, urllib
    
    def path2url(path):
        return urlparse.urljoin(
          'file:', urllib.pathname2url(path))
    
    0 讨论(0)
提交回复
热议问题