日々精進

新しく学んだことを書き留めていきます

JupyterNotebookで親階層のモジュールをimportする方法

ディレクトリ階層が以下のようになっている場合。 grand_parent_dir > parent_dir > child_dir parent_dir/init.pyに書いている関数をimportして使いたいとする。 child_dirの下にJupyterNotebookがあるとする。 その場合、JupyterNotebookで以下のように書いても読み込めない。

from ..parent_dir import func

Jupyterは親階層のファイルを読み込めないため。(多分セキュリティ的な問題で) でも以下のようにsys.pathにpathを追加すると読み込めるようになる。 注意点としては、parent_dirまでのpathを追加してもだめで、grand_parent_dirまでのpathを追加しないといけない。 でないとparent_dir/init.py内の関数をimportできなかった。

import sys, os
from pathlib import Path
sys.path.append(str(Path(os.path.dirname(os.path.abspath("__file__"))).parent.parent))

参考:

stackoverflow.com