Access folder that a custom python function resides in
<p>How do I access a folder that a python function resides in?</p>

<p>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. </p>

<p>My example attempts are:</p>

<pre><code>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
</code></pre>

<p>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?</p>

<p>Like this:  </p>

<pre><code>import os

my_dir = os.path.dirname(__file__)
fname = 'file_path_in_the_function_folder.txt'
filepath = os.path.join(my_dir, fname)
</code></pre>

<p>As explained in the <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__file__" rel="nofollow">data model</a>, you can use the <code>__file__</code> 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.</p>

python