2

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?

1
  • Path . is reative to current working directory, which is directory from which the proecss was started, not the path to current "py" file. Use variable __file__ for that. Commented Oct 5, 2016 at 23:37

1 Answer 1

1

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, 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Putting my_dir = os.path.dirname(file) inside the function in a separate .py file and importing it gives me an error message saying: IndentationError: unindent does not match any outer indentation level...
nevermind, it works perfectly. Somehow my vim messed up the file. Thank you!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.