Access Data in Installed Python Package

Python
How to access data files in installed python packages.
Author

Ziyue Li

Published

November 30, 2022

For a python package structured as the following:

setup.py
src/
  mypkg/
    __init__.py
      module.py
      data/
        tables.csv

we can include the data in the package by

setup(...,
      packages=['mypkg'],
      package_dir={'mypkg': 'src/mypkg'},
      package_data={'mypkg': ['data/*']},
     )

in setup.py.

If we need to access the data files in other parts of this package, we can do

import pkg_resources

DATA_PATH = pkg_resources.resource_filename('mypkg', 'data/')
TABLE_PATH = pkg_resources.resource_filename('mypkg', 'data/tables.csv')

This makes sure to get the path to the data included in the package after installation.