0

I want to access the name of a jupyter notebook from within that juypyter notebook. I need the name, because I want to import a small .py file containing some helper code. This heatmap_axes.py file is outside the folder, where the notebook is. So I am using an approach from here. This approach requires my to access the name of the current file with __file__, but that doesn't seem to work in the jupyter notebook.

That is the code:

script_dir = os.path.dirname(__file__)
module_dir = os.path.join(script_dir, '..')
sys.path.append(module_dir)
from heatmap_axes import set_date_ticks

When I run the code, I get an error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2232/3919301704.py in <module>
     21 from distutils.spawn import find_executable
     22 
---> 23 script_dir = os.path.dirname(__file__)
     24 module_dir = os.path.join(script_dir, '..')
     25 sys.path.append(module_dir)

NameError: name '__file__' is not defined

OK, I could write the name of the notebook on my own, but I need to import this helper .py file in several notebooks, so I want an automated solution. Copying the .py file inside the folder with the notebooks also is not an option, because I have many directories containg notebooks, and I don't want to have to copy this .py file in each of these directories.

That is, what the file-structure looks like:

heatmap_axes.py
nb01\
   <somenotebookname>.ipynb
    ...
nb02\
    <somenotebookname>.ipynb
    ...
nb03\
...
Andre
  • 321
  • 1
  • 12

1 Answers1

0

Solved:

script_dir = os.path.abspath('')

found here.

Andre
  • 321
  • 1
  • 12