importlib.resources
-- 套件資源的讀取、開啟與存取¶
原始碼:Lib/importlib/resources/__init__.py
在 3.7 版被加入.
This module leverages Python's import system to provide access toresourceswithinpackages.
"Resources" are file-like resources associated with a module or package inPython. The resources may be contained directly in a package, within asubdirectory contained in that package, or adjacent to modules outside apackage. Resources may be text or binary. As a result, Python module sources(.py) of a package and compilation artifacts (pycache) are technicallyde-facto resources of that package. In practice, however, resources areprimarily those non-Python artifacts exposed specifically by the packageauthor.
Resources can be opened or read in either binary or text mode.
Resources are roughly akin to files inside directories, though it's importantto keep in mind that this is just a metaphor. Resources and packagesdonot have to exist as physical files and directories on the file system:for example, a package and its resources can be imported from a zip file usingzipimport
.
備註
This module provides functionality similar topkg_resourcesBasicResource Accesswithout the performance overhead of that package. This makes readingresources included in packages easier, with more stable and consistentsemantics.
The standalone backport of this module provides more informationonusing importlib.resources andmigrating from pkg_resources to importlib.resources.
Loaders
that wish to support resource reading should implement aget_resource_reader(fullname)
method as specified byimportlib.resources.abc.ResourceReader
.
- classimportlib.resources.Anchor¶
Represents an anchor for resources, either a
moduleobject
or a module name as a string. Defined asUnion[str,ModuleType]
.
- importlib.resources.files(anchor:Anchor|None=None)¶
Returns a
Traversable
objectrepresenting the resource container (think directory) and its resources(think files). A Traversable may contain other containers (thinksubdirectories).anchor is an optional
Anchor
. If the anchor is apackage, resources are resolved from that package. If a module,resources are resolved adjacent to that module (in the same packageor the package root). If the anchor is omitted, the caller's moduleis used.在 3.9 版被加入.
在 3.12 版的變更:package parameter was renamed toanchor.anchor can nowbe a non-package module and if omitted will default to the caller'smodule.package is still accepted for compatibility but will raisea
DeprecationWarning
. Consider passing the anchor positionally orusingimportlib_resources>=5.10
for a compatible interfaceon older Pythons.
- importlib.resources.as_file(traversable)¶
Given a
Traversable
object representinga file or directory, typically fromimportlib.resources.files()
,return a context manager for use in awith
statement.The context manager provides apathlib.Path
object.Exiting the context manager cleans up any temporary file or directorycreated when the resource was extracted from e.g. a zip file.
Use
as_file
when the Traversable methods(read_text
, etc) are insufficient and an actual file or directory onthe file system is required.在 3.9 版被加入.
在 3.12 版的變更:Added support fortraversable representing a directory.
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 tothe 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 requirean explicitencoding argument if multiplepath_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.
Seethe introduction fordetails onanchor andpath_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 版的變更:Multiplepath_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.
Seethe introduction fordetails onanchor andpath_names.encoding anderrors have the same meaning as in built-in
open()
.For backward compatibility reasons, theencoding argument must be givenexplicitly if there are multiplepath_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 版的變更:Multiplepath_names are accepted.encoding anderrors must be given as keyword arguments.
- importlib.resources.read_binary(anchor,*path_names)¶
Read and return the contents of the named resource as
bytes
.Seethe introduction fordetails onanchor andpath_names.
This function is roughly equivalent to:
files(anchor).joinpath(*path_names).read_bytes()
在 3.13 版的變更:Multiplepath_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.Seethe introduction fordetails onanchor andpath_names.encoding anderrors have the same meaning as in built-in
open()
.For backward compatibility reasons, theencoding argument must be givenexplicitly if there are multiplepath_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 版的變更:Multiplepath_names are accepted.encoding anderrors must be given as keyword arguments.
- importlib.resources.path(anchor,*path_names)¶
Provides the path to theresource as an actual file system path. Thisfunction 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 requiresan actual file system path; it can be used like this:withimportlib.resources.path(anchor,"resource.txt")asfspath:result=fspath.stat()
Seethe introduction fordetails onanchor andpath_names.
This function is roughly equivalent to:
as_file(files(anchor).joinpath(*path_names))
在 3.13 版的變更:Multiplepath_names are accepted.encoding anderrors 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.Seethe introduction fordetails onanchor andpath_names.
This function is roughly equivalent to:
files(anchor).joinpath(*path_names).is_file()
在 3.13 版的變更:Multiplepath_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.Seethe introduction fordetails onanchor andpath_names.
This function is roughly equivalent to:
forresourceinfiles(anchor).joinpath(*path_names).iterdir():yieldresource.name
在 3.11 版之後被棄用:Prefer
iterdir()
as above, which offers more control over theresults and richer functionality.