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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 27 22:17:18 EDT 2009


En Mon, 27 Jul 2009 17:53:12 -0300, Dave Angel <davea at ieee.org> escribió:
> Piotrek wrote:
>>
>> I write a Python program. It will contain some images (in .png format),  
>> some
>> audio files (as .ogg) etc. Now I think where should my installer put  
>> these
>> files and how should I access them. What is the normal Python way of  
>> doing
>> 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?
>>
>>
> My answer is to put read-only files right with the py* files, and  
> writable files in the user's space.  In the former case, you can find  
> the files by parsing __file__ for one of your modules.  In the latter  
> case, it's system dependent.

For those read-only resources I'd use pkgutil.get_data (instead of
manually parsing __file__):

http://docs.python.org/library/pkgutil.html#pkgutil.get_data

It's easier to manage when someone later decide to install the package as
an egg file, or distribute it using py2exe. Quoting the documentation:

"""The function returns a binary string that is the contents of the
specified resource.

For packages located in the filesystem, which have already been imported,
this is the rough equivalent of:

d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()
return data
"""

-- 
Gabriel Genellina




More information about the Python-list mailing list