Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find path of python_notebook.ipynb when running it with Google Colab

I want to find the cwd where my CODE file is stored.

With jupiter Lab i would do:

import os 
cwd= os.getcwd()
print (cwd)
OUT: 
'C:...\\Jupiter_lab_notebooks\\CODE'

However,if i copy the folders to my GoogleDrive, and run the notebook in GOOGLE COLAB, i get:

import os 
cwd= os.getcwd()
print (cwd)
OUT: 
/content

No matter where my notebook is stored. How do i find the actual path my .ipynb folder is stored in?

#EDIT

What i am looking for is python code that will return the location of the COLAB notebook no matter where in drive it is stored. This way i can navigate to sub-folders from there.

like image 848
Leo Avatar asked Feb 12 '21 16:02

Leo


People also ask

How do I find the path of a Jupyter file?

Right-click on a file or directory and select “Copy Shareable Link” to copy a URL that can be used to open JupyterLab with that file or directory open. Right-click on a file or directory and select “Copy Path” to copy the filesystem relative path.

Where are Ipynb files stored?

ipynb in my current working directory, it is saved in my python/Scripts folder.

How do I give a dataset path in Google Colab?

Click on the dataset in your repository, then click on View Raw. Copy the link to the raw dataset and store it as a string variable called url in Colab as shown below (a cleaner method but it's not necessary). The last step is to load the url into Pandas read_csv to get the dataframe.


1 Answers

This problem has been bothering me for a while, this code should set the working directory if the notebook has been singularly found, limited to Colab system and mounted drives, this can be run on Colab:

import requests
import urllib.parse
import google.colab
import os

google.colab.drive.mount('/content/drive')


def locate_nb(set_singular=True):
    found_files = []
    paths = ['/']
    nb_address = 'http://172.28.0.2:9000/api/sessions'
    response = requests.get(nb_address).json()
    name = urllib.parse.unquote(response[0]['name'])

    dir_candidates = []

    for path in paths:
        for dirpath, subdirs, files in os.walk(path):
            for file in files:
                if file == name:
                    found_files.append(os.path.join(dirpath, file))

    found_files = list(set(found_files))

    if len(found_files) == 1:
        nb_dir = os.path.dirname(found_files[0])
        dir_candidates.append(nb_dir)
        if set_singular:
            print('Singular location found, setting directory:')
            os.chdir(dir_candidates[0])
    elif not found_files:
        print('Notebook file name not found.')
    elif len(found_files) > 1:
        print('Multiple matches found, returning list of possible locations.')
        dir_candidates = [os.path.dirname(f) for f in found_files]

    return dir_candidates

locate_nb()
print(os.getcwd())
like image 127
H_Barrio Avatar answered Oct 06 '22 00:10

H_Barrio