Application resources

Previous sections in this guide have described how to load images, media and text documents using pyglet. Applications also usually have the need to load other data files: for example, level descriptions in a game, internationalised strings, and so on.

Programmers are often tempted to load, for example, an image required by their application with:

image = pyglet.image.load('logo.png')

This code assumes logo.png is in the current working directory. Unfortunately the working directory is not necessarily the same as the directory containing the application script files.

A common workaround for this is to construct a path relative to the script file instead of the working directory:

import os

script_dir = os.path.dirname(__file__)
path = os.path.join(script_dir, 'logo.png')
image = pyglet.image.load(path)

This, besides being tedious to write, still does not work for resources within ZIP files, and can be troublesome in projects that span multiple packages.

The pyglet.resource module solves this problem elegantly:

image = pyglet.resource.image('logo.png')

The following sections describe exactly how the resources are located, and how the behaviour can be customised.