importlib.resources -- Package resource reading, opening and access

ソースコード: Lib/importlib/resources/__init__.py


バージョン 3.7 で追加.

This module leverages Python's import system to provide access to resources within packages.

"Resources" are file-like resources associated with a module or package in Python. The resources may be contained directly in a package, within a subdirectory contained in that package, or adjacent to modules outside a package. Resources may be text or binary. As a result, Python module sources (.py) of a package and compilation artifacts (pycache) are technically de-facto resources of that package. In practice, however, resources are primarily those non-Python artifacts exposed specifically by the package author.

Resources can be opened or read in either binary or text mode.

リソースは大体ディレクトリの中のファイルに似ていますが、これは単なる例え話であることを頭に入れておくことが重要です。例えば、パッケージとそのリソースは zipimport を使って zip ファイルからインポートすることができます。

注釈

このモジュールは、 pkg_resources Basic Resource Access に似た機能を、そのパッケージのパフォーマンスのオーバーヘッドを伴わずに提供します。 これにより、パッケージに含まれるリソースの読み込みがより簡単になり、より安定した一貫した意味付けができるようになります。

このモジュールのスタンドアローンバックポートでは、 importlib.resources の使用pkg_resources から importlib.resources への移行 についての詳細情報を提供しています。

Loaders でリソースの読み込みをサポートしたい場合は、 importlib.resources.abc.ResourceReader で指定された get_resource_reader(fullname) メソッドを実装しなければいけません。

class importlib.resources.Anchor

Represents an anchor for resources, either a module object or a module name as a string. Defined as Union[str, ModuleType].

importlib.resources.files(anchor: Anchor | None = None)

Returns a Traversable object representing the resource container (think directory) and its resources (think files). A Traversable may contain other containers (think subdirectories).

anchor is an optional Anchor. If the anchor is a package, resources are resolved from that package. If a module, resources are resolved adjacent to that module (in the same package or the package root). If the anchor is omitted, the caller's module is used.

バージョン 3.9 で追加.

バージョン 3.12 で変更: package parameter was renamed to anchor. anchor can now be a non-package module and if omitted will default to the caller's module. package is still accepted for compatibility but will raise a DeprecationWarning. Consider passing the anchor positionally or using importlib_resources >= 5.10 for a compatible interface on older Pythons.

importlib.resources.as_file(traversable)

Given a Traversable object representing a file or directory, typically from importlib.resources.files(), return a context manager for use in a with statement. The context manager provides a pathlib.Path object.

Exiting the context manager cleans up any temporary file or directory created 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 on the file system is required.

バージョン 3.9 で追加.

バージョン 3.12 で変更: Added support for traversable representing a directory.

非推奨の関数

古い、非推奨の関数群はまだ利用可能ですが、Pythonの将来のバージョンで削除される予定です。これらの関数の主な欠点は、ディレクトリをサポートしていないことです:それらはすべてのリソースが パッケージ 内に直接配置されていると想定しています。

importlib.resources.Package

関数が Package を引数に取る場合、 module object またはモジュール名を文字列で渡すことができます。渡すことができるのは、 __spec__.submodule_search_locationsNone 以外のモジュールオブジェクトのみです。

Package 型は Union[str, ModuleType] として定義されています。

バージョン 3.12 で非推奨.

importlib.resources.Resource

以下の関数の resource 引数には、リソース名を文字列または path-like オブジェクト として渡すことができます。

Resource 型は Union[str, os.PathLike] として定義されています。

importlib.resources.open_binary(package, resource)

パッケージ 内の リソース をバイナリ読み取り用に開きます。

packagePackage の要件に従った名前またはモジュールオブジェクトです。 resourcepackage 内で開くリソースの名前です。パス区切り文字を含むことはできず、サブリソースを持つことはできません(つまり、ディレクトリにはなれません)。 この関数は、バイナリI/Oストリームを読み込むために開いている typing.BinaryIO のインスタンスを返します。

バージョン 3.11 で非推奨: この関数の呼び出しは、次のように置き換えることができます:

files(package).joinpath(resource).open('rb')
importlib.resources.open_text(package, resource, encoding='utf-8', errors='strict')

package 内の resource をテキスト読み取り用に開きます。 デフォルトでは、リソースはUTF-8として読み取り用に開かれます。

packagePackage の要件に従った名前またはモジュールオブジェクトです。 resourcepackage 内で開くリソースの名前です。パス区切り文字を含むことはできず、サブリソースを持つことはできません(つまり、ディレクトリにはなれません)。 encodingerrors は、組み込みの open() と同じ意味を持ちます。

この関数は、テキストI/Oストリームを読み込むために開いている typing.TextIO のインスタンスを返します。

バージョン 3.11 で非推奨: この関数の呼び出しは、次のように置き換えることができます:

files(package).joinpath(resource).open('r', encoding=encoding)
importlib.resources.read_binary(package, resource)

package 内の resource の内容を読み取り、 bytes として返します。

packagePackage の要件に従った名前またはモジュールオブジェクトです。 resourcepackage 内で開くリソースの名前です。パス区切り文字を含むことはできず、サブリソースを持つことはできません(つまり、ディレクトリにはなれません)。この関数は、リソースの内容を bytes として返します。

バージョン 3.11 で非推奨: この関数の呼び出しは、次のように置き換えることができます:

files(package).joinpath(resource).read_bytes()
importlib.resources.read_text(package, resource, encoding='utf-8', errors='strict')

package 内の resource の内容を読み込んで str として返します。デフォルトでは、内容は厳密なUTF-8として読み込まれます。

packagePackage の要件に従った名前またはモジュールオブジェクトです。 resourcepackage 内で開くリソースの名前です。パス区切り文字を含むことはできず、サブリソースを持つことはできません(つまり、ディレクトリにはなれません)。 encodingerrors は、組み込みの open() と同じ意味を持ちます。この関数は、リソースの内容を str として返します。

バージョン 3.11 で非推奨: この関数の呼び出しは、次のように置き換えることができます:

files(package).joinpath(resource).read_text(encoding=encoding)
importlib.resources.path(package, resource)

resource へのパスを実際のファイルシステムのパスとして返します。この関数は、 with 文で使用するためのコンテキストマネージャを返します。コンテキストマネージャは pathlib.Path オブジェクトを提供します。

コンテキストマネージャーを終了すると、例えば zip ファイルからリソースを抽出する必要がある場合に作成される一時ファイルを削除します。

packagePackage の要件に従った名前またはモジュールオブジェクトです。 resourcepackage 内で開くリソースの名前です。パス区切り文字を含むことはできず、サブリソースを持つことはできません(つまり、ディレクトリにはなれません)。

バージョン 3.11 で非推奨: この関数の呼び出しは、 as_file(): を使って置き換えることができます:

as_file(files(package).joinpath(resource))
importlib.resources.is_resource(package, name)

パッケージ内に name という名前のリソースがある場合は True を、ない場合は False を返します。この関数は、ディレクトリをリソースとみなしません。 package は、名前か Package の要件に準拠したモジュールオブジェクトです。

バージョン 3.11 で非推奨: この関数の呼び出しは、次のように置き換えることができます:

files(package).joinpath(resource).is_file()
importlib.resources.contents(package)

パッケージ内の名前付きアイテムに対するイテラブルを返します。 イテラブルは str リソース(ファイルなど)と非リソース(ディレクトリなど)を返します。イテラブルは、サブディレクトリへの再帰は行いません。

package は、名前または Package の要件に適合するモジュールオブジェクトのいずれかです。

バージョン 3.11 で非推奨: この関数の呼び出しは、次のように置き換えることができます:

(resource.name for resource in files(package).iterdir() if resource.is_file())