Managing resources in a Python project

Viewed 48669

I have a Python project in which I am using many non-code files. Currently these are all images, but I might use other kinds of files in the future. What would be a good scheme for storing and referencing these files?

I considered just making a folder "resources" in the main directory, but there is a problem; Some images are used from within sub-packages of my project. Storing these images that way would lead to coupling, which is a disadvantage.

Also, I need a way to access these files which is independent on what my current directory is.

4 Answers

The new way of doing this is with importlib. For Python versions older than 3.7 you can add a dependency to importlib_resources and do something like

from importlib_resources import files


def get_resource(module: str, name: str) -> str:
    """Load a textual resource file."""
    return files(module).joinpath(name).read_text(encoding="utf-8")

If your resources live inside the foo/resources sub-module, you would then use get_resource like so

resource_text = get_resource('foo.resources', 'myresource')
Related