importlib.resources
-- 包资源的读取、打开和访问¶
源代码: Lib/importlib/resources/__init__.py
Added in version 3.7.
此模块调整了 Python 的导入系统以便提供对 包 内部的 资源 的访问。
“资源”是指 Python 中与模块或包相关联的文件类资源。 资源可以直接包含在某个包中,包含在某个包的子目录中,或是与某个包外部的模块相邻。 资源可以是文本或二进制数据。 因此,从技术上说 Python 包的模块源代码文件 (.py) 和编译结果文件 (pycache) 就是包实际所包含的资源。 但是,在实践中,资源主要是指包作者专门公开的非 Python 文件。
资源可以使用二进制或文本模式打开。
资源大致相当于目录内的文件,不过需要记住这只是一个比喻。 资源和包 不是 必须如文件系统上的物理文件和目录那样存在的:例如,一个包及其资源可使用 zipimport
从一个 ZIP 文件导入。
备注
本模块提供了类似于 pkg_resources Basic Resource Access 的功能而没有那样高的性能开销。 这使得读取包中的资源更为容易,并具有更为稳定和一致的语义。
此模块的独立向下移植版本在 using importlib.resources 和 migrating from pkg_resources to importlib.resources 中提供了更多信息。
想要支持资源读取的 加载器
应当实现 importlib.resources.abc.ResourceReader
中规定的 get_resource_reader(fullname)
方法。
- importlib.resources.files(anchor: Anchor | None = None)¶
返回一个代表资源容器(相当于目录)及其资源(相当于文件)的
Traversable
对象。 Traversable 可以包含其他容器(相当于子目录)。anchor 是一个可选的
Anchor
。 如果 anchor 是一个包,则会从这个包获取资源。 如果是一个模块,则会从这个模块的相邻位置获取资源(在同一个包或包的根目录中)。 如果省略了 anchor,则会使用调用方的模块。Added in version 3.9.
在 3.12 版本发生变更: package 形参被重命名为 anchor。 anchor 现在可以是一个不为包的模块,如果被省略则默认为调用方的模块。 为保持兼容性 package 仍然被接受但会引发
DeprecationWarning
。 请考虑以位置参数方式传入或使用importlib_resources >= 5.10
作为针对旧版 Python 的兼容接口。
- importlib.resources.as_file(traversable)¶
给定一个代表文件或目录的
Traversable
对象,通常是来自importlib.resources.files()
,返回一个上下文管理器以供with
语句使用。 该上下文管理器提供一个pathlib.Path
对象。退出上下文管理器后会清除从 zip 文件等提取资源时创建的任何临时文件或目录。
当 Traversable 的方法(如
read_text
等)不足以满足需要而需要文件系统中的真实文件或目录时请使用as_file
。Added in version 3.9.
在 3.12 版本发生变更: 增加了对代表目录的 traversable 的支持。
Functional API¶
A set of simplified, backwards-compatible helpers is available. These allow common operations in a single function call.
For all the following functions:
anchor is an
Anchor
, as infiles()
. Unlike infiles
, it may not be omitted.path_names are components of a resource's path name, relative to the anchor. For example, to get the text of resource named
info.txt
, use:importlib.resources.read_text(my_module, "info.txt")
Like
Traversable.joinpath
, The individual components should use forward slashes (/
) as path separators. For example, the following are equivalent:importlib.resources.read_binary(my_module, "pics/painting.png") importlib.resources.read_binary(my_module, "pics", "painting.png")
For backward compatibility reasons, functions that read text require an explicit encoding argument if multiple path_names are given. For example, to get the text of
info/chapter1.txt
, use:importlib.resources.read_text(my_module, "info", "chapter1.txt", encoding='utf-8')
- importlib.resources.open_binary(anchor, *path_names)¶
Open the named resource for binary reading.
See the introduction for details on anchor and path_names.
This function returns a
BinaryIO
object, that is, a binary stream open for reading.This function is roughly equivalent to:
files(anchor).joinpath(*path_names).open('rb')
在 3.13 版本发生变更: Multiple path_names are accepted.
- importlib.resources.open_text(anchor, *path_names, encoding='utf-8', errors='strict')¶
Open the named resource for text reading. By default, the contents are read as strict UTF-8.
See the introduction for details on anchor and path_names. encoding and errors have the same meaning as in built-in
open()
.For backward compatibility reasons, the encoding argument must be given explicitly if there are multiple path_names. This limitation is scheduled to be removed in Python 3.15.
This function returns a
TextIO
object, that is, a text stream open for reading.This function is roughly equivalent to:
files(anchor).joinpath(*path_names).open('r', encoding=encoding)
在 3.13 版本发生变更: Multiple path_names are accepted. encoding and errors must be given as keyword arguments.
- importlib.resources.read_binary(anchor, *path_names)¶
Read and return the contents of the named resource as
bytes
.See the introduction for details on anchor and path_names.
This function is roughly equivalent to:
files(anchor).joinpath(*path_names).read_bytes()
在 3.13 版本发生变更: Multiple path_names are accepted.
- importlib.resources.read_text(anchor, *path_names, encoding='utf-8', errors='strict')¶
Read and return the contents of the named resource as
str
. By default, the contents are read as strict UTF-8.See the introduction for details on anchor and path_names. encoding and errors have the same meaning as in built-in
open()
.For backward compatibility reasons, the encoding argument must be given explicitly if there are multiple path_names. This limitation is scheduled to be removed in Python 3.15.
This function is roughly equivalent to:
files(anchor).joinpath(*path_names).read_text(encoding=encoding)
在 3.13 版本发生变更: Multiple path_names are accepted. encoding and errors must be given as keyword arguments.
- importlib.resources.path(anchor, *path_names)¶
Provides the path to the resource as an actual file system path. This function returns a context manager for use in a
with
statement. The context manager provides apathlib.Path
object.Exiting the context manager cleans up any temporary files created, e.g. when the resource needs to be extracted from a zip file.
For example, the
stat()
method requires an actual file system path; it can be used like this:with importlib.resources.path(anchor, "resource.txt") as fspath: result = fspath.stat()
See the introduction for details on anchor and path_names.
This function is roughly equivalent to:
as_file(files(anchor).joinpath(*path_names))
在 3.13 版本发生变更: Multiple path_names are accepted. encoding and errors must be given as keyword arguments.
- importlib.resources.is_resource(anchor, *path_names)¶
Return
True
if the named resource exists, otherwiseFalse
. This function does not consider directories to be resources.See the introduction for details on anchor and path_names.
This function is roughly equivalent to:
files(anchor).joinpath(*path_names).is_file()
在 3.13 版本发生变更: Multiple path_names are accepted.
- importlib.resources.contents(anchor, *path_names)¶
Return an iterable over the named items within the package or path. The iterable returns names of resources (e.g. files) and non-resources (e.g. directories) as
str
. The iterable does not recurse into subdirectories.See the introduction for details on anchor and path_names.
This function is roughly equivalent to:
for resource in files(anchor).joinpath(*path_names).iterdir(): yield resource.name
自 3.11 版本弃用: Prefer
iterdir()
as above, which offers more control over the results and richer functionality.