0

I an writing a Python package. The index like bellow

main.py
pkg
|--utils.py
|--files
   |--1.txt
   |--2.txt

I write a function to load the file 1.txt in the utils.py using relative path. And it works in the utils.py, but fail when I call the function in the main.py.

I konw the reason is the relative path has changed. I want to know how to solve it with not change the relative path.

Another problems is how to add the file to the python package when upload to the pipy.

imhuay
  • 271
  • 1
  • 2
  • 11
  • I find a similiar question, https://stackoverflow.com/questions/4519127/setuptools-package-data-folder-location – imhuay Apr 17 '18 at 04:41

1 Answers1

0

The best way to handle this is by assigning files/* as package_data and using pkg_resources.resource_filename. In your setup.py, assuming your package is named "pkg", add the following inside of setup():

package_data={'pkg': ['files/*']}

Then to use:

import pkg_resources
filepath = pkg_resources.resource_filename('pkg', '1.txt')
jordanm
  • 33,009
  • 7
  • 61
  • 76