summaryrefslogtreecommitdiff
path: root/content/blog/jupyterlab_notebook_file_oneliner/index.rst
blob: 8885c4ca58fafbf178aec44ddb750834ca20caac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
---
title: "Getting the .ipynb Notebook File Location From a Running Jupyter Lab Notebook"
date: 2025-06-30T23:42:00+01:00
summary: >
    If you need to get the path of the ipynb file in a running #Jupyter notebook, this one-liner will do the trick. It
    seems chatgpt is confused, and a bunch of other approaches on the web look fragile and/or unnecessarily complex to
    me.
---

If you need to get the path of the ipynb file in a running #Jupyter notebook, this one-liner will do the trick. It seems
chatgpt is confused, and a bunch of other approaches on the web look fragile and/or unnecessarily complex to me.

.. code:: python

    import sys
    Path(json.loads(Path(sys.argv[-1]).read_bytes())['jupyter_session'])

The way this works is that for each notebook, jupyter starts a python "kernel" process that actually runs the notebook's
code. That kernel gets a json file with info on the notebook's location on the disk passed through its command line.
Since we're running code in that exact python process, we can just grab that json file from sys.argv, and read it
ourselves.