I am trying to avoid using sys.path.append...or any hacks and want to organise the folders. Given I have a notebook .ipynb file, how can I import .py files if I place them in a directory ?
Asked
Active
Viewed 59 times
1 Answers
0
If you place them in the same directory, you can import your module (.py
) files easily with:
from my_module import * # This will import all functions
from my_module import foo # This will import only my_module.foo
foo()
or simply import the module
import my_module
my_module.foo()
Refer to this python documentation for more explanation about module.
Update on updated question
As per this answer, you can use the above approach if you upload your module. Just ensure your pwd
is correct.
Better yet in the sample, you can define __init__.py
inside your module folder (refer to section 6.4. Packages in the doc above) to do something like:
from folder.my_module import foo
foo()

Darren Christopher
- 3,893
- 4
- 20
- 37
-
Not when you run from Colaboratory http://colab.research.google.com , the above won't work. You can append the path and that works but there must be a cleaner way. – KamaliOS Sep 20 '19 at 12:49
-
@KamaliOS you should’ve mention this is specific to google colab in your question. Your current question is about python notebook in general. – Darren Christopher Sep 20 '19 at 12:53
-
My mistake. Updated. Thanks. – KamaliOS Sep 20 '19 at 12:54