0

I have created a python package. In the __init__.py there is a line that reads

from ._constants import initial_time, final_time, time_step

When these variables are imported from the module _constants.py the code in the in this file is executed which reads some data from a folder that is located next to the package (i.e. some data in this file is read using relative paths like '../data/file.csv'.

The problem is that I am importing this python package from a script outside of it which causes a FileNotFoundError since these paths are now relative to where the package is imported not where the file is that is reading that data.

I could see this type of setup being a common use case where some reference datasets need to be loaded when a package is imported. For example, in statsmodels there are reference statistical datasets that can be used to test some of the functionality of the package.

What is the "proper" way to load up data in a python package so that when the package is imported the files are found and the relative paths used to find them still work?

Here is an example directory structure to illustrate what I mentioned above:

project/
    data/
        file.csv
    package/
        __init__.py
    main.py

Note: I know that I can change the paths some that they are relative to main.py. I've already done that and need a more general solution now that I am writing tests and need to import some things to a different location from the package.

martineau
  • 119,623
  • 25
  • 170
  • 301
pbreach
  • 16,049
  • 27
  • 82
  • 120
  • 1
    [this](http://stackoverflow.com/questions/918154/relative-paths-in-python) is what you're looking for I think. – Alex Nov 20 '16 at 18:17
  • I think this would work. I'll have to refactor all the paths in `_constants.py` but it still might be the simplest option. – pbreach Nov 20 '16 at 18:28
  • It worked! There were 80 filenames to be changed but a simple regex made this easy. Although the solution is the same as the question you linked I don't think this question is a duplicate. Feel free to post an answer if you'd like. – pbreach Nov 20 '16 at 18:47
  • You can determine what folder the currently executing file is in by using `os.path.dirname(__file__)`. With that you should be able to determine the path to the data file. – martineau Nov 20 '16 at 19:11

0 Answers0