2

I'm importing helpers.py file from <project_root>/lib/helpers.py location to one of the sub-folder in my project. I am using sys package. But I'm getting ModuleNotFound error while importing.

Given below is the code I'm using.

import sys
sys.path.insert(0, '/d/Development/s5-data-analysis/lib/')
import helpers

The sub-folder is /d/Development/s5-data-analysis/notebooks/my.ipynb . What is the correct way of importing this helper.py to my.ipnb .

3 Answers 3

2

This looks to me like you are using Git Bash on Windows (or some other Unix-Windows-Layer), which has its own builtin path translation. Other programs like will only be able to use the usual path names, in this case d:\Development\s5-data-analysis\lib:

sys.path.insert(0, r"d:\Development\s5-data-analysis\lib")
Sign up to request clarification or add additional context in comments.

Comments

0

You can convert lib folder into a package, by adding __init__.py to lib folder. In this file, you can import helpers module like this:

from . import helpers

Finally, on your actual codefile, import helpers module like this:

from lib import helpers

3 Comments

Still getting the error "ImportError: cannot import name 'helpers'"
I'm trying to import my Python file to Jupyter notebook
I like to learn more around creating packages. Thanks for the answer. Feel free to share a useful link with me to learn on creating packages :)
0

There are various ways through which you can import.

Example 1, Import a python module with python interpreter:

1.Put this in /home/el/foo/fox.py:

def what_does_the_fox_say():
print("vixens cry")

2.Get into the python interpreter:

 nag@sahil:/home/el/foo$ python
 Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
 >>> import fox
 >>> fox.what_does_the_fox_say()
 vixens cry
 >>> 

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

1.Put this in /home/el/foo2/mylib.py:

def moobar():
print("hi")

2.Put this in /home/el/foo2/main.py:

execfile("/home/el/foo2/mylib.py")
moobar()

Example 3. Use from ... import ... functionality:

1.Put this in /home/el/foo3/chekov.py:

def question():
print "where are the nuclear wessels?"

2.Put this in /home/el/foo3/main.py:

from chekov import question
question()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.