use pkg_resources
This package gets installed with setuptools.
From package docstring:
Docstring:
Package resource API
--------------------
A resource is a logical file contained within a package, or a logical
subdirectory thereof. The package resource API expects resource names
to have their path parts separated with ``/``, *not* whatever the local
path separator is. Do not use os.path operations to manipulate resource
names being passed into the API.
The package resource API is designed to work with normal filesystem packages,
.egg files, and unpacked .egg files. It can also work in a limited way with
.zip files and with custom PEP 302 loaders that support the ``get_data()``
method.
In case, you install your package with zip_safe = False
, your data will be available in directory.
Installing with zip_safe = True
, it will be part of egg. But if you need to use the files from there, it is very easy and pkg_resources
provides nice set of functions and methods
- pkg_resources.resource_exists
- pkg_resources.resource_isdir
- pkg_resources.resource_stream - provides file-like object
- pkg_resources.resource_filename
- pkg_resources.resource_listdir
- pkg_resources.resource_string
Note, that this works even for zipsafe True installations.
Just put your data into directory relative to your package direcotry. And then from your code:
import pkg_resources
fname = pkg_resources.resource_filename("your.package.name", "folder/example1.txt")
use it only for statical files
Do not attempt to have there any files, which are changing. Technically it could be possible (with zip_safe = False
the files are just there), but it is definitely bad design (permission, updates of packages).
Do not init your project from pip
, better provide some appinit
command
Using pip
to install your data into application directory is real abuse.
I would recommend to define a command installed by our program, like appinit
, and use it whenever you need to populate your directory. Commands like buildout
(installed by zc.buildout
) and others are often using this patter.