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.
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.
ipynb in my current working directory, it is saved in my python/Scripts folder.
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.
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())
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With