pythonpathjupyter-notebookgoogle-colaboratorygetcwd

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.


Solution

  • 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())