Access files relative to imported python module
<p>Preliminary:</p>

<p>I have Anaconda 3 on Windows 10, and a folder, <code>folder_default</code>, that I have put on the Python path. I'm not actually sure whether that's the right terminology, so to be clear: regardless to where my Python script is, if I have a line of code that says <code>import myFile</code>, that line of code will succeed if <code>myFile.py</code> is in <code>folder_default</code>.</p>

<p>My issue:</p>

<p>In <code>folder_default</code>, I have:</p>

<ol>
<li>A subfolder called <code>useful_files</code> which contains a text file called <code>useful_file_1.txt</code>.</li>
<li>A python script called <code>my_misc.py</code>.</li>
</ol>

<p><code>my_misc.py</code> has a line similar to: <code>np.loadtxt('useful_files/useful_file_1.txt')</code>. This line does not work if I use <code>import my_script</code> in a python file in a location other than <code>folder_default</code>, since <code>useful_files/useful_file_1.txt</code> is not the folder path relative to the python file that imports <code>my_misc.py</code>. I don't want to start using global file paths if I can avoid it.</p>

<p>How can I access files using file paths relative to the imported python module, rather than relative to the python script that imports that module?</p>

<p>Please let me know if the question is unclear - I tried to write a fake, minimal version of the setup that's actually on my computer in the hopes that that would simplify things, but I can change it if that actually makes things more confusing.</p>

<p>Thanks.</p>

<p>You can get the path to current module using the <code>getfile</code> method of <code>inspect</code> module as <code>inspect.getfile(inspect.currentframe())</code>.
For example:</p>

<pre><code># File : my_misc.py
import os, inspect

module_dir_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # get path to the directory of current module
useful_file_path = os.path.join(module_dir_path,'useful_files','useful_file_1.txt')
# path stored in useful_file_path. do whatever you want!

np.loadtxt(useful_file_path)
</code></pre>

python import relative-path python-import