How do I refer to a data file relative to a package or installation directory?
Peter L Hansen
peter at engcorp.com
Sat Oct 9 14:57:20 CEST 2004
> I have a package that includes some data files. I am planning to use a
> distutils setup script to install the package. How can I compute a path
> name for such a data file that will always be relative to my package
> root directory (i.e. both when installed, and in my development directory?)
> Or to rephrase, say the data file is mypkg/data/foo.dat relative to the
> package root "mypkg" (the directory that holds __init__.py). Is there an
> enquiry that will return the absolute path prefix for mypkg?
Presumably you meant that relative to the package root "mypkg",
the data file is actually at "data/foo.dat", or as some might
write it "./data/foo.dat"? If not, you've got an extra layer
there confusing things.
Basically, just use __file__ inside the __init__.py module to find
that file's location, then use os.path.split() to pull off the
path part and os.path.join() to add the "data/foo.dat" part.
If that's not enough, please post some kind of code snippet
to help explain things better.
More information about the Python-list