Skip to content
Advertisement

Jupyter import Python function

I have the following folder structure

main/
     jupyter/
            nb.ipynb
     helper/
           text.txt
           foo/
              foo.py

The file foo.py contains

def foo():
    open("../text.txt", "r")

In the jupyter notebook I have

import sys
sys.path.append("../helper/foo")
from foo import foo

foo()

which gives a file not found error. What’s the cleanest way of fixing that? (If possible, I’d like to keep foo.py unchanged.)

Advertisement

Answer

You get this error because the path is relative to your working directory. You will need to change it using os.chdir('../helper/foo').

It would be a bit better to change foo.py and use os.path.join(os.path.dirname(os.path.dirname(__file__)), 'text.txt') as path.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement