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:
thefile=open('test.csv')
or:
thefile=open('../somedirectory/test.csv')
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:
path=getBasePathOfProject()+'/somedirectory/test.csv'
thefile=open(path)
Is this the right way? Is it possible?
I spent a long time figuring out the answer to this, but I finally got it (and it's actually really simple):
This will append the relative path of your subfolder to the directories for python to look in It's pretty quick and dirty, but it works like a charm :)
Try to use a filename relative to the current files path. Example for './my_file':
In Python 3.4+ you can also use pathlib:
You also try to normalize your
cwd
usingos.path.abspath(os.getcwd())
. More info here.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
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
Example:
The advantage is that its guaranteed to work even if it is an archive distribution like an egg.
See http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api
I often use something similar to this:
The variable
holds the file name of the script you write that code in, so you can make paths relative to script, but still written with absolute paths. It works quite well for several reasons:
But you need to watch for platform compatibility - Windows' os.pathsep is different than UNIX.
You can use the build in
__file__
variable. It contains the path of the current file. I would implement getBaseOfProject in a module in the root of your project. There I would get the path part of__file__
and would return that. This method can then be used everywhere in your project.