Wayne Day
Wayne Day

Reputation: 41

Set working directory for Google Colab notebook to Drive location of the notebook

I'm trying to set the working directory for a Google Colab notebook to the location where the notebook resides in Google Drive without manually copying-pasting the folderpath. The motivation is to allow copies of the notebook to function in place and dynamically set the working directory to the location of the notebook without having to manually copy and paste the location to the code.

I have code to mount the notebook to Google Drive and know how to set the working directory but would like to have a section of code that identifies the location of the notebook and stores it as a variable/object.

## Mount notebook to Google Drive
from google.colab import drive
drive.mount("/content/drive", force_remount=True)

## Here is where i'd like to save the folderpath of the notebook
## for example, I would like root_path to ultimately be a folder named "Research" located in a Shared Drive named "Projects"
## root_path should equal '/content/drive/Shared drives/Projects/Research'
## the notebook resides in this "Research" folder

## then change the working directory to root_path
os.chdir(root_path)

Upvotes: 4

Views: 6917

Answers (1)

korakot
korakot

Reputation: 40928

This is quite complicated. You need to get the current notebook's file_id. Then look up all its parents and get their names.

# all imports, login, connect drive
import os
from pathlib import Path
import requests
from google.colab import auth
auth.authenticate_user()
from googleapiclient.discovery import build
drive = build('drive', 'v3').files()

# recursively get names
def get_path(file_id):
  f = drive.get(fileId=file_id, fields='name, parents').execute()
  name = f.get('name')
  if f.get('parents'):
    parent_id = f.get('parents')[0]  # assume 1 parent
    return get_path(parent_id) / name
  else:
    return Path(name)

# change directory
def chdir_notebook():
  d = requests.get('http://172.28.0.2:9000/api/sessions').json()[0]
  file_id = d['path'].split('=')[1]
  path = get_path(file_id)
  nb_dir = '/content/drive' / path.parent
  os.chdir(nb_dir)
  return nb_dir

Now you just call chdir_notebook(), and it will change to the orginal directory of that notebook.

And don't forget to connect to your Google Drive first.

Here's a workable notebook

I simplify all these and now have added it to my library.

!pip install kora -q
from kora import drive
drive.chdir_notebook()

Upvotes: 5

Related Questions