Gerardo Zinno
Gerardo Zinno

Reputation: 1732

Can't import module situated in parent folder from Jupyter-lab notebook and pathlib.Path

Here's my situation. I have some jupyter notebooks inside some folder and I would like to share some code between those notebooks trough a library I made.

The folder structure is the following:

1.FirstFolder/
    notebookA.ipynb
2.SecondFolder/
    notebookB.ipynb
mylib/
    __init__.py
    otherfiles.py

I tried putting the following code at the beginning of the notebook:

# to use modules in parent folder
import sys
import os
from pathlib import Path
libpath = os.path.join(Path.cwd().parent,'mylib')
print(f"custom library functions are in the module:\n\t{libpath}")
sys.path.append(libpath)
import mylib

The print outputs the correct path of the module and then a ModuleNotFoundError comes up and the program crashes:

---> 10 import mylib
     11 from mylib import *

ModuleNotFoundError: No module named 'mylib'

Looking up on SO I found that that should have been the way to import a module from a non-default folder. Where is the error?

EDIT: after FinleyGibson's answer I tried sys.path.append(Path.cwd().parent) and restarted the kernel but I still have the same problem.

EDIT2: I tried this and it worked, but I still would like to know why the previous approaches haven't worked.

import sys
import os
from pathlib import Path
tmp = Path.cwd()
os.chdir(Path.cwd().parent)
sys.path.append(Path.cwd())
import mylib
from mylib.dataloading import *
os.chdir(tmp)

Upvotes: 7

Views: 3199

Answers (2)

FinleyGibson
FinleyGibson

Reputation: 921

You have added the contents of os.path.join(Path.cwd().parent,'mylib') to your path, this means python will look inside this dir for the module you are importing. mylib is not located in this dir, but rather the parent dir. Also Path.cwd().parent returns a pathlib.PosixPath object. Convert this to a string to use it with import (or, just use sys.path.append('../'):

try:

import sys
import os
from pathlib import Path
sys.path.append(str(Path.cwd().parent))
import mylib

doing this allows me to import a variable X = 'import success' located in otherfiles.py like so:

ans = mylib.otherfiles.X
print(ans)

>>> 'import success'

Upvotes: 5

Tushar Koley
Tushar Koley

Reputation: 164

I think Jupiter is not able to locate the folder of your module.

First cell use

cd ..

then in the next cell - then it should work

import mylib 

Upvotes: 3

Related Questions