# sdl2.ext.resources - Resource Management

Nearly every application or game includes resources, such as image and data files, configuration files and so on. Accessing those files from an asset folder hierarchy or a compressed bundle across platforms can become a complex task. The `Resources` class aims to simplify this by providing dictionary-style access for your application’s resources.

Let’s assume your application has the following installation layout:

    Application Directory
        Application.py
        Application.conf
        data/
            background.jpg
            button1.jpg
            button2.jpg
            info.dat

Within the `Application.py` code, you can - completely system-agnostic - define a new resource that keeps track of all `data` items.

    apppath = os.path.dirname(os.path.abspath(__file__))
    appresources = Resources(os.path.join(apppath, "data"))

    # Access some images
    bgimage = appresources.get("background.jpg")
    btn1image = appresources.get("button1.jpg")
    ...

To access individual files, you do not need to concat paths the whole time and regardless of the current directory, your application operates on, you can access your resource files at any time through the `Resources` instance, you created initially.

The `Resources` class is also able to scan an index archived files, compressed via ZIP or TAR (gzip or bzip2 compression), and subdiectories automatically.

    Application Directory
        Application.py
        Application.conf
        data/
            audio/
                example.wav
            background.jpg
            button1.jpg
            button2.jpg
            graphics.zip
                [tileset1.bmp
                 tileset2.bmp
                 tileset3.bmp
                 ]
            info.dat

    tilesimage = appresources.get("tileset1.bmp")
    audiofile = appresources.get("example.wav")

If you request an indexed file via `Resources.get()`, you will receive a `io.BytesIO` stream, containing the file data, for further processing.

Note

The scanned files act as keys within the `Resources` class. This means that two files, that have the same name, but are located in different directories, will not be indexed. Only one of them will be accessible through the `Resources` class.

## API

sdl2.ext.resources.open_zipfile(archive, filename, directory=None)

  Retrieves a given file from a ZIP archive.

  Parameters:

    - archive (`ZipFile`, str) – The ZipFile object or path to the ZIP archive containing the desired file.

    - filename (str) – The name of the file to retrieve from the archive.

    - directory (str, optional) – The path to the directory within the archive containing the file to retrieve. Defaults to the root level of the archive.

  Returns:

    A Python bytestream object containing the requested file.

  Return type:

    `BytesIO`

  Raises:

    - KeyError – If the given file could not be found within the archive.

    - TypeError – If the archive is not a valid ZIP archive.

sdl2.ext.resources.open_tarfile(archive, filename, directory=None, ftype=None)

  Retrieves a given file from a TAR archive.

  If the TAR archive uses `.tar.gz` or `.tar.bz2` compression and the file name does not contain either of these identifiers, the compression type must be manually specified.

  Parameters:

    - archive (`TarFile`, str) – The TarFile object or path to the TAR archive containing the desired file.

    - filename (str) – The name of the file to retrieve from the archive.

    - directory (str, optional) – The path to the directory within the archive containing the file to retrieve. Defaults to the root level of the archive.

    - ftype (str, optional) – The compression type (if any) used for the TAR file, can be either ‘gz’, ‘bz2’, or None (no compression). If not specified, will default to assuming no compression.

  Returns:

    A Python bytestream object containing the requested file.

  Return type:

    `BytesIO`

  Raises:

    - KeyError – If the given file could not be found within the archive.

    - TypeError – If the archive is not a supported TAR archive.

class sdl2.ext.resources.Resources(path=None, subdir=None, excludepattern=None)

  A container class for managing application resource files.

  This class eases access to resources by allowing access using relative paths, scanning archives to locate files, and more.

  Parameters:

    - path (str, optional) – The path of a resource directory with which to initialze the container. Defaults to `None`.

    - subdir (str, optional) – Deprecated, do not use.

    - excludepattern (str, optional) – A regular expression indicating which directories (if any) to ignore if initializing the container with a resource path. Defaults to `None`.

  add(filename)

    Adds a file to the Resources container.

    If the given file is a supported archive, its contents will be scanned and added to the container.

    Parameters:

      filename (str) – The filepath of the resource to add to the container.

    Raises:

      ValueError – If the file does not exist at the provided path.

  add_file(filename)

    Adds a file without scanning to the Resources container.

    Unlike `add()`, this method will not attempt to add the contents of any provided archives to the container.

    Parameters:

      filename (str) – The filepath of the resource to add to the container.

    Raises:

      ValueError – If the file does not exist at the provided path.

  add_archive(filename, typehint='zip')

    Adds a `.zip` or `.tar` archive to the container.

    This will scan the passed archive and add its contents to the list of available resources. Currently `.zip`, `.tar`, `.tar.bz2`, and `.tar.gz` formats are supported.

    Parameters:

      - filename (str) – The filepath of the archive to scan and add to the container.

      - typehint (str, optional) – The format of the archive to add to the container, required if using a custom file extension. Must be one of `zip`, `tar`, `tarbz2`, or `targz`. Defaults to `zip` if not specified.

    Raises:

      ValueError – If the file does not exist at the provided path, or if the file is not a supported archive type.

  get(filename)

    Retrieves a resource file by name from the container.

    Parameters:

      filename (str) – The file name of the resource to retrieve.

    Returns:

      A Python bytestream object containing the retrieved resource file.

    Return type:

      `BytesIO`

    Raises:

      KeyError – If the given file could not be found.

  get_path(filename)

    Gets the path of a given resource file.

    If the file is only available within an archive, a string in the form `filename@archivename` will be returned.

    Parameters:

      filename (str) – The file name of the resource to locate.

    Returns:

      The absolute path of the resource file, or the archive identifier string if the resource is inside an archive.

    Return type:

      str

    Raises:

      KeyError – If the given file could not be found.

  scan(path, subdir=None, excludepattern=None)

    Scans a path, adding all matching files to the container.

    If a located file is a `.zip` or `.tar` archive, its contents will be indexed and added to the container automatically.

    Parameters:

      - path (str) – The path of the directory to scan.

      - subdir (str, optional) – Deprecated, do not use.

      - excludepattern (str, optional) – A regular expression indicating which directories (if any) within the file structure of the given path to exclude from indexing. Defaults to `None`.

    Raises:

      ValueError – If the specified path does not exist.