Ryan Ryan - 1 year ago 70
Python Question

Using package files from script

If I have a script in my Python package, how can I get it to read other files from the package, since

contains (for example)
and not

(The files are just templates, not modules.)

Answer Source

You could use the ResourceManager API from setuptools' pkg_resources:

import pkg_resources
my_stream = pkg_resources.resource_stream(__name__, "foo.dat")

will open my.package/my/package/foo.dat as the file-like object my_stream for example.

This will work for regular as well as zipped eggs. Note however that this requires setuptools to be installed. For a solution that only uses the standard library (which is to be preferred), see @abarnert's answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download