1:mod:`!importlib.resources` -- Package resource reading, opening and access 2--------------------------------------------------------------------------- 3 4.. module:: importlib.resources 5 :synopsis: Package resource reading, opening, and access 6 7**Source code:** :source:`Lib/importlib/resources/__init__.py` 8 9-------------- 10 11.. versionadded:: 3.7 12 13This module leverages Python's import system to provide access to *resources* 14within *packages*. 15 16"Resources" are file-like resources associated with a module or package in 17Python. The resources may be contained directly in a package, within a 18subdirectory contained in that package, or adjacent to modules outside a 19package. Resources may be text or binary. As a result, Python module sources 20(.py) of a package and compilation artifacts (pycache) are technically 21de-facto resources of that package. In practice, however, resources are 22primarily those non-Python artifacts exposed specifically by the package 23author. 24 25Resources can be opened or read in either binary or text mode. 26 27Resources are roughly akin to files inside directories, though it's important 28to keep in mind that this is just a metaphor. Resources and packages **do 29not** have to exist as physical files and directories on the file system: 30for example, a package and its resources can be imported from a zip file using 31:py:mod:`zipimport`. 32 33.. note:: 34 35 This module provides functionality similar to `pkg_resources 36 <https://setuptools.readthedocs.io/en/latest/pkg_resources.html>`_ `Basic 37 Resource Access 38 <https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access>`_ 39 without the performance overhead of that package. This makes reading 40 resources included in packages easier, with more stable and consistent 41 semantics. 42 43 The standalone backport of this module provides more information 44 on `using importlib.resources 45 <https://importlib-resources.readthedocs.io/en/latest/using.html>`_ and 46 `migrating from pkg_resources to importlib.resources 47 <https://importlib-resources.readthedocs.io/en/latest/migration.html>`_. 48 49:class:`Loaders <importlib.abc.Loader>` that wish to support resource reading should implement a 50``get_resource_reader(fullname)`` method as specified by 51:class:`importlib.resources.abc.ResourceReader`. 52 53.. class:: Anchor 54 55 Represents an anchor for resources, either a :class:`module object 56 <types.ModuleType>` or a module name as a string. Defined as 57 ``Union[str, ModuleType]``. 58 59.. function:: files(anchor: Optional[Anchor] = None) 60 61 Returns a :class:`~importlib.resources.abc.Traversable` object 62 representing the resource container (think directory) and its resources 63 (think files). A Traversable may contain other containers (think 64 subdirectories). 65 66 *anchor* is an optional :class:`Anchor`. If the anchor is a 67 package, resources are resolved from that package. If a module, 68 resources are resolved adjacent to that module (in the same package 69 or the package root). If the anchor is omitted, the caller's module 70 is used. 71 72 .. versionadded:: 3.9 73 74 .. versionchanged:: 3.12 75 *package* parameter was renamed to *anchor*. *anchor* can now 76 be a non-package module and if omitted will default to the caller's 77 module. *package* is still accepted for compatibility but will raise 78 a :exc:`DeprecationWarning`. Consider passing the anchor positionally or 79 using ``importlib_resources >= 5.10`` for a compatible interface 80 on older Pythons. 81 82.. function:: as_file(traversable) 83 84 Given a :class:`~importlib.resources.abc.Traversable` object representing 85 a file or directory, typically from :func:`importlib.resources.files`, 86 return a context manager for use in a :keyword:`with` statement. 87 The context manager provides a :class:`pathlib.Path` object. 88 89 Exiting the context manager cleans up any temporary file or directory 90 created when the resource was extracted from e.g. a zip file. 91 92 Use ``as_file`` when the Traversable methods 93 (``read_text``, etc) are insufficient and an actual file or directory on 94 the file system is required. 95 96 .. versionadded:: 3.9 97 98 .. versionchanged:: 3.12 99 Added support for *traversable* representing a directory. 100 101 102.. _importlib_resources_functional: 103 104Functional API 105^^^^^^^^^^^^^^ 106 107A set of simplified, backwards-compatible helpers is available. 108These allow common operations in a single function call. 109 110For all the following functions: 111 112- *anchor* is an :class:`~importlib.resources.Anchor`, 113 as in :func:`~importlib.resources.files`. 114 Unlike in ``files``, it may not be omitted. 115 116- *path_names* are components of a resource's path name, relative to 117 the anchor. 118 For example, to get the text of resource named ``info.txt``, use:: 119 120 importlib.resources.read_text(my_module, "info.txt") 121 122 Like :meth:`Traversable.joinpath <importlib.resources.abc.Traversable>`, 123 The individual components should use forward slashes (``/``) 124 as path separators. 125 For example, the following are equivalent:: 126 127 importlib.resources.read_binary(my_module, "pics/painting.png") 128 importlib.resources.read_binary(my_module, "pics", "painting.png") 129 130 For backward compatibility reasons, functions that read text require 131 an explicit *encoding* argument if multiple *path_names* are given. 132 For example, to get the text of ``info/chapter1.txt``, use:: 133 134 importlib.resources.read_text(my_module, "info", "chapter1.txt", 135 encoding='utf-8') 136 137.. function:: open_binary(anchor, *path_names) 138 139 Open the named resource for binary reading. 140 141 See :ref:`the introduction <importlib_resources_functional>` for 142 details on *anchor* and *path_names*. 143 144 This function returns a :class:`~typing.BinaryIO` object, 145 that is, a binary stream open for reading. 146 147 This function is roughly equivalent to:: 148 149 files(anchor).joinpath(*path_names).open('rb') 150 151 .. versionchanged:: 3.13 152 Multiple *path_names* are accepted. 153 154 155.. function:: open_text(anchor, *path_names, encoding='utf-8', errors='strict') 156 157 Open the named resource for text reading. 158 By default, the contents are read as strict UTF-8. 159 160 See :ref:`the introduction <importlib_resources_functional>` for 161 details on *anchor* and *path_names*. 162 *encoding* and *errors* have the same meaning as in built-in :func:`open`. 163 164 For backward compatibility reasons, the *encoding* argument must be given 165 explicitly if there are multiple *path_names*. 166 This limitation is scheduled to be removed in Python 3.15. 167 168 This function returns a :class:`~typing.TextIO` object, 169 that is, a text stream open for reading. 170 171 This function is roughly equivalent to:: 172 173 files(anchor).joinpath(*path_names).open('r', encoding=encoding) 174 175 .. versionchanged:: 3.13 176 Multiple *path_names* are accepted. 177 *encoding* and *errors* must be given as keyword arguments. 178 179 180.. function:: read_binary(anchor, *path_names) 181 182 Read and return the contents of the named resource as :class:`bytes`. 183 184 See :ref:`the introduction <importlib_resources_functional>` for 185 details on *anchor* and *path_names*. 186 187 This function is roughly equivalent to:: 188 189 files(anchor).joinpath(*path_names).read_bytes() 190 191 .. versionchanged:: 3.13 192 Multiple *path_names* are accepted. 193 194 195.. function:: read_text(anchor, *path_names, encoding='utf-8', errors='strict') 196 197 Read and return the contents of the named resource as :class:`str`. 198 By default, the contents are read as strict UTF-8. 199 200 See :ref:`the introduction <importlib_resources_functional>` for 201 details on *anchor* and *path_names*. 202 *encoding* and *errors* have the same meaning as in built-in :func:`open`. 203 204 For backward compatibility reasons, the *encoding* argument must be given 205 explicitly if there are multiple *path_names*. 206 This limitation is scheduled to be removed in Python 3.15. 207 208 This function is roughly equivalent to:: 209 210 files(anchor).joinpath(*path_names).read_text(encoding=encoding) 211 212 .. versionchanged:: 3.13 213 Multiple *path_names* are accepted. 214 *encoding* and *errors* must be given as keyword arguments. 215 216 217.. function:: path(anchor, *path_names) 218 219 Provides the path to the *resource* as an actual file system path. This 220 function returns a context manager for use in a :keyword:`with` statement. 221 The context manager provides a :class:`pathlib.Path` object. 222 223 Exiting the context manager cleans up any temporary files created, e.g. 224 when the resource needs to be extracted from a zip file. 225 226 For example, the :meth:`~pathlib.Path.stat` method requires 227 an actual file system path; it can be used like this:: 228 229 with importlib.resources.path(anchor, "resource.txt") as fspath: 230 result = fspath.stat() 231 232 See :ref:`the introduction <importlib_resources_functional>` for 233 details on *anchor* and *path_names*. 234 235 This function is roughly equivalent to:: 236 237 as_file(files(anchor).joinpath(*path_names)) 238 239 .. versionchanged:: 3.13 240 Multiple *path_names* are accepted. 241 *encoding* and *errors* must be given as keyword arguments. 242 243 244.. function:: is_resource(anchor, *path_names) 245 246 Return ``True`` if the named resource exists, otherwise ``False``. 247 This function does not consider directories to be resources. 248 249 See :ref:`the introduction <importlib_resources_functional>` for 250 details on *anchor* and *path_names*. 251 252 This function is roughly equivalent to:: 253 254 files(anchor).joinpath(*path_names).is_file() 255 256 .. versionchanged:: 3.13 257 Multiple *path_names* are accepted. 258 259 260.. function:: contents(anchor, *path_names) 261 262 Return an iterable over the named items within the package or path. 263 The iterable returns names of resources (e.g. files) and non-resources 264 (e.g. directories) as :class:`str`. 265 The iterable does not recurse into subdirectories. 266 267 See :ref:`the introduction <importlib_resources_functional>` for 268 details on *anchor* and *path_names*. 269 270 This function is roughly equivalent to:: 271 272 for resource in files(anchor).joinpath(*path_names).iterdir(): 273 yield resource.name 274 275 .. deprecated:: 3.11 276 Prefer ``iterdir()`` as above, which offers more control over the 277 results and richer functionality. 278