Relative imports in Jupyter notebooks

How do we import a module from a .py or a .ipynb file into a Jupyter notebook from a different directory?
I wrote this post after answering a question on stackoverflow:

For example, if we have the directory structure:


How do we access the file or the notebook configuration_nb.ipynb?

The nbimporter module helps us here:

pip install nbimporter


class Configuration():
    def __init__(self):
        print('hello from')


import nbimporter
from src import configuration

new = configuration.Configuration()


hello from

We can also import and use modules from other notebooks. If you have configuration_nb.ipynb in the /src module:


class Configuration_nb():
    def __init__(self):
        print('hello from configuration notebook')


import nbimporter
from src import configuration_nb

new = configuration_nb.Configuration_nb()


Importing Jupyter notebook from ......\src\configuration_nb.ipynb
hello from configuration notebook

Leave a Reply

Your email address will not be published. Required fields are marked *