将Google Colab笔记本的工作目录设置为Drive的笔记本位置

时间:2020-07-23 16:44:32

标签: python google-colaboratory

我正在尝试将Google Colab笔记本的工作目录设置为笔记本在Google云端硬盘中的驻留位置,而无需手动复制-粘贴文件夹路径。这样做的动机是允许笔记本的副本就位,并动态地将工作目录设置为笔记本的位置,而不必手动复制并将位置粘贴到代码中。

我有将笔记本安装到Google云端硬盘的代码,并且知道如何设置工作目录,但是我想使用一段代码来标识笔记本的位置并将其存储为变量/对象。

## 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)

1 个答案:

答案 0 :(得分:1)

这很复杂。您需要获取当前笔记本的file_id。然后查找其所有父母并获得他们的名字。

# 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

现在您只需调用chdir_notebook(),它将切换到该笔记本的原始目录。

别忘了先连接到您的Google云端硬盘。

这里是workable notebook

我简化了所有这些操作,现在将其添加到我的库中。

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