繁体   English   中英

将 Google Colab 笔记本的工作目录设置为笔记本的驱动器位置

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

我正在尝试将 Google Colab 笔记本的工作目录设置为笔记本在 Google Drive 中所在的位置,而无需手动复制粘贴文件夹路径。 其动机是允许将笔记本复制到 function 并动态地将工作目录设置为笔记本的位置,而无需手动将位置复制并粘贴到代码中。

我有将笔记本挂载到 Google Drive 的代码,并且知道如何设置工作目录,但我希望有一段代码可以识别笔记本的位置并将其存储为变量/对象。

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

这是相当复杂的。 您需要获取当前笔记本的 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 云端硬盘。

这是一个实用的笔记本

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM