将文件名转换为file://URL

2024-06-26 14:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

在WeasyPrint的公共API中,我接受HTML输入的文件名(以及其他类型)。任何与内置open()一起工作的文件名都应该可以工作,但我需要将其转换为file://方案中的URL,该方案稍后将传递给urllib.urlopen()

(所有内容在内部都是URL格式的。为了用urlparse.urljoin()解析相对URL引用,我需要一个文档的“基本URL”。)

urllib.pathname2url是一个开始:

Convert the pathname path from the local syntax for a path to the form used in the path component of a URL. This does not produce a complete URL. The return value will already be quoted using the quote() function.

重点是我的,但我需要一个完整的网址。到目前为止,这似乎是可行的:

def path2url(path):
    """Return file:// URL from a filename."""
    path = os.path.abspath(path)
    if isinstance(path, unicode):
        path = path.encode('utf8')
    return 'file:' + urlparse.pathname2url(path)

UTF-8似乎是由RFC 3987 (IRI)推荐的。但在这种情况下(URL最终是指urllib)也许我应该使用sys.getfilesystemencoding()

然而,基于the literature,我不应该只准备file:,而应该准备file://。。。除非我不应该这样做:在Windows上,nturl2path.pathname2url()的结果已经以三个斜杠开头。

所以问题是:有没有更好的方法来做到这一点并使之跨平台?


Tags: thepathfromapiurl类型return文件名
3条回答

为了完整起见,在Python3.4+中,您应该执行以下操作:

import pathlib

pathlib.Path(absolute_path_string).as_uri()

以上@danodonovan的评论。

对于Python3,以下代码将起作用:

from urllib.parse import urljoin
from urllib.request import pathname2url

def path2url(path):
    return urljoin('file:', pathname2url(path))

我不确定这些文件是否足够严格来保证,但我认为这在实践中是可行的:

import urlparse, urllib

def path2url(path):
    return urlparse.urljoin(
      'file:', urllib.pathname2url(path))

相关问题 更多 >