path to data files

D

Daniel Fetchinson

If a python module requires a data file to run how would I reference
this data file in the source in a way that does not depend on whether
the module is installed system-wide, installed in $HOME/.local or is
just placed in a directory from where the interpreter is fired up? I'd
like to always keep the python source and the data file in the same
directory, be it /usr/lib/python2.6/site-packages,
$HOME/.local/lib/python2.6/site-packages or
/arbitrary/path/to/somewhere.

If the data file is called 'foo' and I simply do open('foo') in the
python source file this will not work if they are both installed
either system-wide or locally. More precisely if the module is called
'foo.py', data file called 'foo', they are both in
/usr/lib/python2.6/site-packages and if foo.py I have open('foo') I'll
get a file not found error.

Any ideas?

Cheers,
Daniel
 
A

Alain Ketterlin

Daniel Fetchinson said:
If a python module requires a data file to run how would I reference
this data file in the source in a way that does not depend on whether
the module is installed system-wide, installed in $HOME/.local or is
just placed in a directory from where the interpreter is fired up?

sys.path[0] is supposed to contain the script's directory.

-- Alain.
 
N

Nobody

If a python module requires a data file to run how would I reference
this data file in the source in a way that does not depend on whether
the module is installed system-wide, installed in $HOME/.local or is
just placed in a directory from where the interpreter is fired up?

sys.path[0] is supposed to contain the script's directory.

One caveat: if you use wxPython, wxversion.select() pushes the directory
containing the selected version at the front of sys.path, so that a
subsequent "import wx" will import the correct version.

It's possible that other functions may do likewise, so if you're
relying upon sys.path[0] to find the script's directory, it's a good idea
to make a copy of sys.path[0] before importing any modules (other than sys).
 
L

Lawrence D'Oliveiro

Daniel said:
If a python module requires a data file to run how would I reference
this data file in the source in a way that does not depend on whether
the module is installed system-wide, installed in $HOME/.local or is
just placed in a directory from where the interpreter is fired up?

You may want to look at the XDG Base Directory Specification
<http://standards.freedesktop.org/basedir-spec/latest/>. There is a python-
xdg module which implements this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top