How to import a module from a different directory and have it look for files in that directory
<p>I'm trying to import a Python module in the directory <code>/home/kurt/dev/clones/ipercron-utils/tester</code>. This directory contains a <code>tester.py</code> and a <code>config.yml</code> file. The <code>tester.py</code> includes the (leading) line</p>

<pre><code>config = yaml.safe_load(open("config.yml"))
</code></pre>

<p>Now, from another directory, I try to import it like so:</p>

<pre><code>import sys
sys.path.insert(0, "/home/kurt/dev/clones/ipercron-utils/tester")
import tester
</code></pre>

<p>However, I get the following error:</p>

<pre><code>Traceback (most recent call last):
  File "/home/kurt/dev/clones/ipercron-compose/controller/controller_debug2.py", line 9, in &lt;module&gt;
    import tester
  File "/home/kurt/dev/clones/ipercron-utils/tester/tester.py", line 28, in &lt;module&gt;
    config = yaml.safe_load(open("config.yml"))
IOError: [Errno 2] No such file or directory: 'config.yml'
</code></pre>

<p>As I understand it, Python is looking for the <code>config.yml</code> file in the current directory (<code>/home/kurt/dev/clones/ipercron-compose/controller</code>) whereas I want it to look in the directory the module was imported from (<code>/home/kurt/dev/clones/ipercron-utils/tester</code>). Is there any way to specify this?</p>

<p><code>__file__</code> always contains the current module filepath (here <code>/home/kurt/dev/clones/ipercron-utils/tester/tester.py</code>).</p>

<p>Just perform a <code>dirname</code> on it => you have the path which contains your <code>yml</code> configuration file.</p>

<p>code it like this in your <code>tester.py</code> module (<code>import os</code> if not already done):</p>

<pre><code>module_dir = os.path.dirname(__file__)
config = yaml.safe_load(open(os.path.join(module_dir,"config.yml")))
</code></pre>

<p>side note: <code>__file__</code> doesn't work on the main file when the code is "compiled" using py2exe. In that case you have to do:</p>

<pre><code>module_dir = os.path.dirname(sys.executable)
</code></pre>

python