title: Python -- import a module from a directory that's not a package
body: <p>I have a directory structure like this...</p>
  
  <pre><code>dir/
    build.py
  dir2
    dir3/
    packages.py
  </code></pre>
  
  <p>Now the <code>build.py</code> needs <code>packages.py</code> -- and note that <code>dir2</code> is not a package.</p>
  
  <p>So what's the best way to get <code>packages.py</code> loaded into <code>build.py</code> (the directory structure can't be changed)</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The <code>sys.path.append</code> solution seems good -- but there is one thing -- I need to use the <code>packages.py</code> file rarely -- and keeping a <code>sys.path</code> that includes a directory that is used rarely, but is at the front -- is that the best thing?</p>
  
  <p><strong>EDIT II</strong></p>
  
  <p>I think the <code>imp</code> solution is best.</p>
  
  <pre><code>import imp    
  packages = imp.load_source('packages', '/path/to/packages.py')
  </code></pre>
  
  <p><strong>EDIT III</strong></p>
  
  <h2>for Python 3.x</h2>
  
  <p>Note that <code>imp.load_source</code> and some other function <a href="http://bugs.python.org/issue14551" rel="noreferrer">have been deprecated</a>. So you should use the <code>imp.load_module</code> today.</p>
  
  <pre><code>fp, pathname, description = imp.find_module('packages', '/path/to/packages.py')
  try:
      mod = imp.load_module('packages', fp, pathname, description)
  finally:
      # since we may exit via an exception, close fp explicitly
      if fp:
          fp.close()
  </code></pre>