HOWTO: Import Python files into Jupyter Notebook while being in another directory.
Almost everyone who works in the field of data science interacts with the Jupyter Notebook tool on a daily basis, and in most cases, they will need to import code from Python code files (.py) in order to use it in this notebook. The code may take the form of functions, classes, or anything else.
However, this process can be tedious at times because these files must be in the same directory for the notebook to find them, and it is not possible to add the path to that directory to the PATH variable using bash commands because it will not be committed. For example:
If we attempt this,
%%bashSRC_DIR=$(cd ..; pwd)
export PATH="${PATH}:$SRC_DIR"
and then print the PATH:
!echo $PATH
Nothing will be added.
Solution
The solution to this is to run the following code:
import os
import sys
directory_path = os.path.abspath(os.path.join('..'))
if directory_path not in sys.path:
sys.path.append(directory_path)
This code will add the path specified in this statement os.path.abspath(os.path.join(‘..’)) to the system PATH variable, allowing you to import…