title: How do I use a relative path in a Python module when the CWD has changed?
body: <p>I have a Python module which uses some resources in a subdirectory of the module directory.  After searching around on stack overflow and finding related answers, I managed to direct the module to the resources by using something like </p>
  
  <pre><code>import os
  os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf')
  </code></pre>
  
  <p>This works fine when I call the module from elsewhere, but it breaks when I call the module after changing the current working directory.  The problem is that the contents of <code>__file__</code> are a relative path, which doesn't take into account the fact that I changed the directory: </p>
  
  <pre><code>&gt;&gt;&gt; mymodule.__file__
  'mymodule/__init__.pyc'
  &gt;&gt;&gt; os.chdir('..')
  &gt;&gt;&gt; mymodule.__file__
  'mymodule/__init__.pyc'
  </code></pre>
  
  <p>How can I encode the absolute path in <code>__file__</code>, or barring that, how can I access my resources in the module no matter what the current working directory is?  Thanks!</p>