We are working with a code repository which is deployed both to Windows and Linux - sometimes on different directories. How should one of the modules inside the project refer to one of the non-Python resources in the project (CSV files, etc.)?
If we do something like:
It will work only when the script is run from one specific directory, or a subset of the directories.
What I would like to do is something like:
Is this the right way? Is it possible?
Try to use a filename relative to the current files path. Example for './my_file':
fn = os.path.join(os.path.dirname(__file__), 'my_file')
In Python 3.4+ you can also use pathlib:
fn = pathlib.Path(__file__).parent / 'my_file'
If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package_resources.
In your case the example would be
import pkg_resources my_data = pkg_resources.resource_string(__name__, "foo.dat")
Which of course reads the resource and the read binary data would be the value of my_data
If you just need the filename you could also use
The advantage is that its guaranteed to work even if it is an archive distribution like an egg.