loco.loop
loco.loop

Reputation: 1597

How to obtain Jupyter Notebook's path?

Is there a function to obtain a Notebook's path?

I've Googled a little on the subject but didn't find a simple way to do it... I want to obtain the Notebook's path so I can then use it elsewhere. This way I could save/use files in the same path as the notebook without worrying about where it got saved.

Right now my solution is to put the following code on top but obviously this poses at least the problem of manually having to execute a cell and also if the working directory changes this will stop working.

import os
current_path = os.getcwd()

Upvotes: 73

Views: 166866

Answers (14)

SeF
SeF

Reputation: 4160

I don't understand the answer saying that you can not do it.

Notebooks are highly dependent on where they are executed and where they live. The specific case would need some special tweak, though in general this may be the answer you were looking for:

from pathlib import Path

Path().cwd()

Edit after @trs feedback:

Thanks for the feedback.

Now, if I understand the problem correctly you are looking for the equivalent of

from pathlib import Path

Path(__file__)

that you would commonly use in a python module, only for a Jupyter notebook.

The closest solution that I could find, when running in vscode, is leveraging on the global() dict:


globals()["__vsc_ipynb_file__"]  # this is the notebook full path

As said above, I think there are and will be edge cases where this will not work, like notebook running in cloud, notebook not in vscode, etc...


Second edit:

Just discovered also


__vsc_ipynb_file__

would work fine to get the filepath on vscode.

Upvotes: -2

rxsen
rxsen

Reputation: 21

I just adopted salhin's suggestion to use extract_module_locals in my answer on this post which explains how to get the current file name and directory both when executed from a .ipynb and a .py file and then use this to navigate relative paths:

import os

try:
    from IPython import get_ipython, extract_module_locals        
    get_ipython

    print("Running from .ipynb file")        

    this_dir, this_filename = os.path.split("/".join(
        extract_module_locals()[1]["__vsc_ipynb_file__"].split("/")[-5:]
    ) )
    print(f'this_dir:\t {this_dir}')
    print(f'this_filename:\t {this_filename}')
    
except:
    print("Running from .py file")
    this_dir, this_filename = os.path.split(os.path.abspath(__file__) )
    print(f'this_dir:\t {this_dir}')
    print(f'this_filename:\t {this_filename}')

# Navigate to file located in one folder up:
os.path.abspath(os.path.join(os.path.dirname(this_dir), 'MyFile.xlsx'))

Upvotes: 0

Arpan Saini
Arpan Saini

Reputation: 5181

Way to identify the path of current notebook where you are running that and to add the relative module to identify any other packages in your project.

 import sys, os

# gives the absolute path of .py and .ipynb where you are running your code. 
os.path.abspath("")

# add the relative module path to sys.path to find any package in your project.   /.. takes to the parent and then you can tranverse to any path.

sys.path.append(os.path.realpath(os.path.abspath("") + '/../utils/'))

Upvotes: 1

user10488833
user10488833

Reputation: 61

By putting locals() into a notebook, I found that there is a __session__ variable containing the path of the notebook file. The post https://stackoverflow.com/a/77904549/10488833 shows that I am not the only one who has found this variable.

Upvotes: 1

Lucas Alonso
Lucas Alonso

Reputation: 188

You are probably using git (if not you should) so I suggest the following approach:

GIT_ROOT_LINES = !git rev-parse --show-toplevel
GIT_ROOT = GIT_ROOT_LINES[0]
GIT_ROOT

And now GIT_ROOT is the path of the directory where .git lives, so you can do whatever you want with it.

Upvotes: -2

salhin
salhin

Reputation: 2654

In VSCode Jupyter, You can try this in a cell:

import IPython
notebook_name = "/".join(
        IPython.extract_module_locals()[1]["__vsc_ipynb_file__"].split("/")[-5:]
    )
print(notebook_name)

Upvotes: 10

Roms
Roms

Reputation: 31

What I am doing is not really beautifull but quite efficient. On VScode, I right click "Copy Path" on a sub folder in my working folder, in which I have my multiples Jupyter Notebook. I remove the end of the string and I obtain the aboslute path to the folder

I after use in one of my jupyter notebook the command: os.chdir(r"path_to_your_folder") and this is it.

NB: Since I work collaborately on repo cointaining Jupyter notebooks, this is the only ugly but efficient solution that I found.

Upvotes: 1

Braden Wiens
Braden Wiens

Reputation: 221

Update:

I found this answer which solves the problem. The following command returns the folder path for both *.py and *.ipynb files.

import os
os.path.abspath("")

I have a bit of a work around to solve this issue but I find that it is often helpful to have for non-notebook projects as well. In the same folder as your notebook create a file called "base_fns.py". Inside this file place the following code:

import os

def get_local_folder():
    return os.path.dirname(os.path.realpath(__file__))

Then, you can get the path to the folder containing base_fns using:

from base_fns import get_local_folder()
rt_fldr = get_local_folder()
print(rt_fldr)

A few notes:

  1. This gives you the absolute path to the folder containing "base_fns.py", not your notebook. If your notebook and base_fns are in the same folder, then the absolute path to the folder for your notebook and base_fns will be the same.
  2. If you place base_fns in a different folder, you will need to know the relative path to navigate from the base_fns folder to your notebook folder.
  3. If you are working on a larger project with a folder structure, you can place base_fns.py in a known folder and then navigate around to find any other folders/files that you may require.

Upvotes: 16

EddieM
EddieM

Reputation: 1

I know this is an old post, but it seems the path to the notebook can be found using os.path.abspath("mynotebook.ipynb")

It's hardcoding the name of the notebook, but that should be relatively easy to keep in sync.

Upvotes: -3

Andres
Andres

Reputation: 1

You can right clic in the Jupyter notebook shortcut icon (in my case under Anaconda3 folder) and go to properties. There you will find the full path to Jupyter: D:\anaconda3\python.exe d:\anaconda3\cwp.py d:\anaconda3 d:\anaconda3\python.exe d:\anaconda3\Scripts\jupyter-notebook-script.py "%USERPROFILE%/"

Properties of Jupyter shortcut:

image

Upvotes: -6

Milin
Milin

Reputation: 9

You can just use "pwd" which stands for print working directory. enter image description here

Upvotes: -5

Mohamed Shamroukh
Mohamed Shamroukh

Reputation: 849

if you can open it you can use this function

1-open your Jupyter notebook 2- write this function 3-it will print out the path

pwd

if not navigate to your python installation folder open folder scripts and there you will find it.

hope this may help others

Upvotes: 3

use this in cell

%%javascript
IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"')
print(nb_name)

Upvotes: 0

Jonas Adler
Jonas Adler

Reputation: 10761

TLDR: You can't

It is not possible to consistently get the path of a Jupyter notebook. See ipython issue #10123 for more information. I'll quote Carreau:

Here are some reasons why the kernel (in this case IPython):

  • may not be running from single file
  • even if one file, the file may not be a notebook.
  • even if notebook, the notebook may not be on a filesystem.
  • even if on a file system, it may not be on the same machine.
  • even if on the same machine the path to the file may not make sens in the IPython context.
  • even if it make sens the Jupyter Protocol has not been designed to do so. And we have no plan to change this abstraction in short or long term.

Your hack works in most cases and is not too bad depending on the situation.

Upvotes: 59

Related Questions