0

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.)

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for the answer. I also think that the second part is actually better. Only a small typo: it should be __file__.
In the grander scheme you could also think about making your helper code an actual package and then load the file with pkgresources. — And thanks for the __FILE__ hint, I was still in C++ mode in my mind.
0

It is sufficient to just go one level up and search there for your folder & module

import sys sys.path.append("../") # just one level higher from folder.module import function function() 

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.