Access folder that a custom python function resides in
Question: How do I access a folder that a python function resides in?

For example, lets say that I have a N by 2 array of data. First column is the
independent variable, and second is the dependent variable. I need to
interpolate this data with different array of independent variable who's range
is contained in the original independent variable. This procedure is used in
multiple different codes with varying range of independent variables such that
I do not want to copy this data file to multiple places. I would like to write
a single function that achieves this, with the single copy of data inside the
folder containing the function itself.

My example attempts are:

    
    
    import numpy as np
    from scipy.interpolate import splev, splrep
    
    def function(some_array):
        filepath = './file_path_in_the_function_folder.txt'
        some_data = np.loadtxt(filepath)
    
        interpolated_data = splev(some_array, splrep(some_data[:,0], some_data[:,1]))
    
        return interpolated_data
    

However, './' does not recognize the location of the function, rather it
directs to the current working directory of the script that imports the
function. How can I circumvent this problem?


Answer: Like this:

    
    
    import os
    
    my_dir = os.path.dirname(__file__)
    fname = 'file_path_in_the_function_folder.txt'
    filepath = os.path.join(my_dir, fname)
    

As explained in the [data
model](https://docs.python.org/3/reference/datamodel.html?highlight=__file__),
you can use the `__file__` name for getting the path of the current module. In
python 3.4+ it's an absolute path, for earlier version you can't easily know
if it's absolute or relative - but you usually needn't care, either.

