Loading resources

Use the pyglet.resource module when files shipped with the application need to be loaded. For example, instead of writing:

data_file = open('file.txt')

use:

data_file = pyglet.resource.file('file.txt')

There are also convenience functions for loading media files for pyglet. The following table shows the equivalent resource functions for the standard file functions.

File function Resource function Type
open pyglet.resource.file File-like object
pyglet.image.load pyglet.resource.image Texture or TextureRegion
pyglet.image.load pyglet.resource.texture Texture
pyglet.image.load_animation pyglet.resource.animation Animation
pyglet.media.load pyglet.resource.media Source
mimetype = text/plain
pyglet.resource.text UnformattedDocument
pyglet.text.load
mimetype = text/html
pyglet.resource.html FormattedDocument
pyglet.text.load
mimetype = text/vnd.pyglet-attributed
pyglet.resource.attributed FormattedDocument
pyglet.font.add_file pyglet.resource.add_font None

pyglet.resource.texture is for loading stand-alone textures, and would be required when using the texture for a 3D model.

pyglet.resource.image is optimised for loading sprite-like images that can have their texture coordinates adjusted. The resource module attempts to pack small images into larger textures for efficient rendering (which is why the return type of this function can be TextureRegion).

Resource locations

Some resource files reference other files by name. For example, an HTML document can contain <img src="image.png" /> elements. In this case your application needs to locate image.png relative to the original HTML file.

Use pyglet.resource.location to get a Location object describing the location of an application resource. This location might be a file system directory or a directory within a ZIP file. The Location object can directly open files by name, so your application does not need to distinguish between these cases.

In the following example, a thumbnails.txt file is assumed to contain a list of image filenames (one per line), which are then loaded assuming the image files are located in the same directory as the thumbnails.txt file:

thumbnails_file = pyglet.resource.file('thumbnails.txt', 'rt')
thumbnails_location = pyglet.resource.location('thumbnails.txt')

for line in thumbnails_file:
    filename = line.strip()
    image_file = thumbnails_location.open(filename)
    image = pyglet.image.load(filename, file=image_file)
    # Do something with `image`...

This code correctly ignores other images with the same filename that might appear elsewhere on the resource path.