简体   繁体   中英

Import local modules in Jupyter notebook

I would like to outsource some general functions useful for multiple notebooks in a module (also for testing purposes). The current directory structure looks like the following

jupyter/
├─ notebooks/
│  ├─ 01 Notebook 1.ipynb
│  ├─ ...
├─ src/
│  ├─ module_a/
│  │  ├─ __init__.py
│  │  ├─ func_a.py
│  ├─ module_b/...
├─ tests/...
├─ data/...
├─ .../

In func_a.py , there is a simple function def print_a(): print('a')

However, when I would like to import and use module_a in 01 Notebook 1.ipynb by using (what I think makes sense)

from .. src.module_a import print_a

I got an ImportError: attempted relative import with no known parent package . What am I doing wrong? I am using Python 3.9.

I would try to append the src directory to the system path like so:

import sys
sys.path.append("/path/to/your/src")

from src.module_a import a

please note that you can use the relative path from your notebook root and not absolute path like in the example above, so the following:

sys.path.append("src")

should work too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM