importlib.resources – Package resource reading, opening and access¶
Source code:Lib/importlib/resources/__init__.py
Added in version 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.
Note
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
moduleobjector a module name as a string. Defined asUnion[str,ModuleType].
- importlib.resources.files(anchor:Anchor|None=None)¶
Returns a
Traversableobjectrepresenting 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.Added in version 3.9.
Changed in version 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.10for a compatible interfaceon older Pythons.
- importlib.resources.as_file(traversable)¶
Given a
Traversableobject representinga file or directory, typically fromimportlib.resources.files(),return a context manager for use in awithstatement.The context manager provides apathlib.Pathobject.Exiting the context manager cleans up any temporary file or directorycreated when the resource was extracted from e.g. a zip file.
Use
as_filewhen the Traversable methods(read_text, etc) are insufficient and an actual file or directory onthe file system is required.Added in version 3.9.
Changed in version 3.12:Added support fortraversable representing a directory.
Functional API¶
An older, previously deprecated set of functions is still available.The main drawback of these functions is that they do not supportdirectories: they assume all resources are located directly within apackage.
- importlib.resources.Package¶
Whenever a function accepts a
Packageargument, you can pass ineither amoduleobjector a module nameas a string. You can only pass module objects whose__spec__.submodule_search_locationsis notNone.The
Packagetype is defined asUnion[str,ModuleType].
- importlib.resources.Resource¶
Forresource arguments of the functions below, you can pass inthe name of a resource as a string ora
path-likeobject.The
Resourcetype is defined asUnion[str,os.PathLike].
- importlib.resources.open_binary(package,resource)¶
Open for binary reading theresource withinpackage.
package is either a name or a module object which conforms to the
Packagerequirements.resource is the name of the resource to openwithinpackage; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory). This function returns atyping.BinaryIOinstance, a binary I/O stream open for reading.This function is roughly equivalent to:
files(package).joinpath(resource).open('rb')
- importlib.resources.open_text(package,resource,encoding='utf-8',errors='strict')¶
Open for text reading theresource withinpackage. By default, theresource is opened for reading as UTF-8.
package is either a name or a module object which conforms to the
Packagerequirements.resource is the name of the resource to openwithinpackage; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory).encoding anderrorshave the same meaning as with built-inopen().This function returns a
typing.TextIOinstance, a text I/O stream openfor reading.This function is roughly equivalent to:
files(package).joinpath(resource).open('r',encoding=encoding)
- importlib.resources.read_binary(package,resource)¶
Read and return the contents of theresource withinpackage as
bytes.package is either a name or a module object which conforms to the
Packagerequirements.resource is the name of the resource to openwithinpackage; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory). This function returns thecontents of the resource asbytes.This function is roughly equivalent to:
files(package).joinpath(resource).read_bytes()
- importlib.resources.read_text(package,resource,encoding='utf-8',errors='strict')¶
Read and return the contents ofresource withinpackage as a
str.By default, the contents are read as strict UTF-8.package is either a name or a module object which conforms to the
Packagerequirements.resource is the name of the resource to openwithinpackage; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory).encoding anderrorshave the same meaning as with built-inopen(). This functionreturns the contents of the resource asstr.This function is roughly equivalent to:
files(package).joinpath(resource).read_text(encoding=encoding)
- importlib.resources.path(package,resource)¶
Return the path to theresource as an actual file system path. Thisfunction returns a context manager for use in a
withstatement.The context manager provides apathlib.Pathobject.Exiting the context manager cleans up any temporary file created when theresource needs to be extracted from e.g. a zip file.
package is either a name or a module object which conforms to the
Packagerequirements.resource is the name of the resource to openwithinpackage; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory).This function is roughly equivalent to
as_file(files(package).joinpath(resource))
- importlib.resources.is_resource(package,name)¶
Return
Trueif there is a resource namedname in the package,otherwiseFalse.This function does not consider directories to be resources.package is either a name or a module object which conforms to thePackagerequirements.This function is roughly equivalent to:
files(package).joinpath(resource).is_file()
- importlib.resources.contents(package)¶
Return an iterable over the named items within the package. The iterablereturns
strresources (e.g. files) and non-resources(e.g. directories). The iterable does not recurse into subdirectories.package is either a name or a module object which conforms to the
Packagerequirements.This function is roughly equivalent to:
(resource.nameforresourceinfiles(package).iterdir()ifresource.is_file())