Module Not found during import in Jupyter Notebook
Solution 1
I'm pretty sure this issue is related and the answer there will help you: https://stackoverflow.com/a/15622021/7458681
tl;dr the cwd of the notebook server is always the base path where you started the server, no matter was running import os os.getcwd()
says. Use import sys sys.path.append("/path/to/your/module/folder")
.
I ran it with some dummy modules in the same structure as you had specified, and before modifying sys.path
it wouldn't run and after it would
Solution 2
two lines of code will solve this,
#list the current work dir
os.getcwd()
#change the current work dir
os.chdir()
change the path, and import module, have fun.
Ryan
Updated on September 11, 2021Comments
-
Ryan over 2 years
I have the following package (and working directory):
WorkingDirectory-- |--MyPackage-- | |--__init__.py | |--module1.py | |--module2.py | |--notebook.ipynb
In
__init__.py
I have:import module1 import module2
If I try to import MyPackage into my notebook:
import MyPackage as mp
I will get
ModuleNotFoundError: No module named 'module1'
. But import works fine if I execute the script outside a notebook: if I createtest.py
in the same directory and do the same as in the notebook the import would work properly. It will work inside the notebook if I use fully qualified name in__init__.py
(import MyPackage.module1
).What's the reason for different import behavior?
I have confirmed the working directory of the notebook is
WorkingDirectory
.---Update---------
Exact error is:
C:\Users\Me\Documents\Working Directory\MyPackage\__init__.py in <module>() ---> 17 import module1 ModuleNotFoundError: No module named 'module1'
My problem differs from the possible duplicate:
The notebook was able to find the package, but only unable to load the module. This was inferred from substituting
module1
withMyPackage.module1
worked well and suggests it may not be a problem related withPATH
.I cded into
WorkingDirectory
and started the server there. The working directory should be the folder containing my package.