How do I import module in jupyter notebook directory into notebooks in lower directories?
<p>I have used jupyter notebook for data analysis for quite sometime. I would like to develop a module in my jupyter notebook directory and be able to import that new module into notebooks. My jupyter notebook file directory can be represented as follows;</p>

<pre><code>Jupyter notebooks\

    notebook1.ipynb

    new_module\
        __init__.py
        newfunction.py

    currentnotebooks\
        notebook2.ipynb
</code></pre>

<p>When use <code>import new_module</code> in notebook1.ipynb it works however when I try the same command in notebook2.ipynb I get the following <code>ImportError: No module named 'new_module'</code>. The two obvious solutions are A) move new_module into the currentnotebooks directory or B) move notebook2.ipynb up to the same level as new_module. I don't want to mess around with the file structure at all. Is this possible?</p>

<p>You need to make sure that the parent directory of <code>new_module</code> is on your python path.  For a notebook that is one level below <code>new_module</code>, this code will do the trick:</p>

<pre><code>import os
import sys
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
    sys.path.append(nb_dir)
</code></pre>

<p>If you're further down in the directory hierarchy, you will need to adjust the way <code>nb_dir</code> is set, but that's all.  You should <em>not</em> run this code for a notebook in <code>Jupyter notebooks</code>, since it would add the parent of that directory to the python path, which is probably undesirable.</p>

<p>The reason the import works for <code>notebook1</code> is that sys.path contains <code>''</code> (the empty string), which is aways the current directory of the running interpreter (kernel, in this case).  A google search for <code>explain python path</code> turns up several good explanations of how pyhton used <code>PYTHONPATH</code> (aka <code>sys.path</code>).</p>

python python-3.x ipython python-import jupyter-notebook