where do I put resources (images, audio files) when I wrote Python program?

Marco Mariani marco at sferacarta.com
Tue Jul 28 04:18:57 EDT 2009


Piotrek wrote:

> that? I think about puting these files in /usr/share/myprogram and then
> reading it the normal way (so the path "/usr/share/myprogram" would be just
> hardwired in my program). Is it the way one usually does it in Python
> program or is there any more sofisticated way?

Just keep them in your sources, and create an empty __init__.py file in 
the images directory.
Then install setuptools and use the pkg_resources module. It will work 
even if your application is installed as an egg through easy_install, 
possibly zipped.


To open a resource file:

f = pkg_resources.resource_stream('path.to.package', 'resource.png')
f.read()


"""
     Return a readable file-like object for the specified resource; it 
may be an actual file, a StringIO, or some similar object. The stream is 
in "binary mode", in the sense that whatever bytes are in the resource 
will be read as-is.
"""



More information about the Python-list mailing list