Import py file in another directory in Jupyter notebook Import py file in another directory in Jupyter notebook python-3.x python-3.x

Import py file in another directory in Jupyter notebook


There is no simple way to import python files in another directory.This is unrelated to the jupyter notebook

Here are 3 solutions to your problem

  1. You can add the directory containing the file you with to import to your path and then import the file. like this
import sys  sys.path.insert(0, '/path/to/application/app/folder')import file
  1. You can create a local module by having an empty __init__.py file in the folder you want to import. There are some weird rules regarding the folder hierarchy that you have to take into consideration.

  2. You can create a module for the file you wish to import and install it globally.


Assuming you have a folder name Jupyter and you wish to import modules (employee) from another folder named nn_webserver.

visualizing it:

enter image description here

do this:

import sysimport osmodule_path = os.path.abspath(os.path.join('..'))if module_path not in sys.path:    sys.path.append(module_path+"\\nn_webserver")from employee import motivation_to_work

see additional information here from @metakermit


I would suggest to install functions.py as a package in your virtual environment. There are some benefits of this:

  1. You can access functions.py file from any iPython notebook located in any place, but at the given environment (kernel).
  2. Once you changed any function in functions.py file, you don't need to reload your iPython notebook again and again. It will automatically reload every change.

This is the way how it can be done:

  • Create setup.py file (https://docs.python.org/2/distutils/setupscript.html) in your project folder
  • Activate your virtual environment, go to your project location, and use this command pip install -e .
  • Then, in your iPython notebook:

    %load_ext autoreload

    %autoreload 1

    %aimport yourproject.functions

    from functions import *

That's it!