0

I have a .mat file in my package that I want to be including when I build the package. I do this with

data_files=[('utide', ['utide/ut_constants.mat'])],

This builds just fine. The question I then have is, when I try to load in the mat file with scipy IO, I have no idea where this file is located, and how I should code it in to be proper. Do I just find the files buildpath and hard code it in? Or is there some more pythonic way to do this?

For anyone interested, the code can be found here.

Wesley Bowman
  • 1,366
  • 16
  • 35

1 Answers1

1

Since ut_constants.mat will be in the utide package directory, you could specify its path like this:

import utide
import os

matfile = os.path.join(os.path.dirname(os.path.abspath(utide.__file__)),
                       'ut_constants.mat')

If you wish to define matfile in __init__.py, then you can find out where utide has been installed by looking at the special variable __file__:

matfile = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                       'ut_constants.mat')
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Should I do this in the function that uses the mat file, or in the __init__.py? – Wesley Bowman May 27 '14 at 12:54
  • Place it in `__init__.py` **only if** you wish to make the `matfile` variable available to users of `utide`. If that is not necessary, I would just use it internally where needed, such as in the function that uses the mat file. – unutbu May 27 '14 at 12:58
  • Well, the file is needed to do the functionality of UTide. Putting it in init i think would be best. What would be the best way to do this? Even for most functions in the package, I have to import numpy in each one that uses numpy. Is there also a way to put that in init so it works in all the functions in the package? Sorry, kind of new to packaging and find the documentation a little unclear on some of this. – Wesley Bowman May 27 '14 at 14:37
  • Although it is allowed, I wouldn't use so many files with just one function in each. You can combine them (if doing so is logical) into one file (module). Along with grouping the function names together in a logical unit (a module namespace), you won't have to `import numpy as np` so many times. Near the top of the module, you might also define [the special variable `__all__`](http://stackoverflow.com/q/44834/190597) to list all the names you wish to be available in the `utide` *package namespace*. Then, in `utide/__init__.py` place `from module import *`. – unutbu May 27 '14 at 16:04
  • Alright, but how do I go about putting the above code into __init__ since in __init__ I dont import utide. How will I find the directory – Wesley Bowman May 27 '14 at 17:14
  • Doh, I'm sorry, I wasn't thinking about that. The answer is to use `__file__` instead of `utide.__file__`. – unutbu May 27 '14 at 17:17