How to get the path of the Databricks Notebook dynamically?

Viewed 1825

Please don't give solution for IPython/Jupyter notebooks. The technology is different.

I want to get the path of my Databricks notebook dynamically. Which is something I can get from the UI "Copy File Path" as shown below. I am not able to use __file__ as that is giving me error.

NameError: name '__file__' is not defined

enter image description here

2 Answers

Each notebook has so-called "context" that contains a lot of information about environment, including the HTTP Path, hostname, etc. It could be retrieved as Python dict with something like this (it's simpler to convert to JSON & back than to fetch fields by .get functions):

import json
ctx = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())

inside the ctx dictionary there is a subdictionary named extraContext, that contains field notebook_path that is what you need:

nb_path = ctx['extraContext']['notebook_path']

If there is anything like that available for you, it can be found by inspecting globals() and locals(), e.g.

print(globals())

In my case, the closest to this I found was:

_dh

e.g.:

print(_dh)
# ['/media/win10/Users/norok2/Downloads']
Related