Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 设置GoogleColab笔记本的工作目录以驱动笔记本的位置_Python_Google Colaboratory - Fatal编程技术网

Python 设置GoogleColab笔记本的工作目录以驱动笔记本的位置

Python 设置GoogleColab笔记本的工作目录以驱动笔记本的位置,python,google-colaboratory,Python,Google Colaboratory,我正在尝试将Google Colab笔记本的工作目录设置为笔记本位于Google Drive中的位置,而无需手动复制粘贴folderpath。其动机是允许笔记本的副本就地运行,并动态地将工作目录设置到笔记本的位置,而无需手动将位置复制并粘贴到代码中 我有将笔记本安装到Google Drive的代码,知道如何设置工作目录,但我希望有一段代码来标识笔记本的位置,并将其存储为变量/对象 ## Mount notebook to Google Drive from google.colab import

我正在尝试将Google Colab笔记本的工作目录设置为笔记本位于Google Drive中的位置,而无需手动复制粘贴folderpath。其动机是允许笔记本的副本就地运行,并动态地将工作目录设置到笔记本的位置,而无需手动将位置复制并粘贴到代码中

我有将笔记本安装到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)

这相当复杂。您需要获取当前笔记本的文件id。然后查找其所有父项并获取其名称

#所有导入、登录、连接驱动器
导入操作系统
从pathlib导入路径
导入请求
从google.colab导入验证
auth.authenticate_user()
从GoogleAppClient.discovery导入生成
drive=build('drive','v3')。files()
#递归地获取名称
def get_路径(文件id):
f=drive.get(fileId=file\u id,fields='name,parents').execute()
name=f.get('name')
如果f.get(‘父母’):
parent_id=f.get('parents')[0]#假设为1个parent
返回get\u路径(父\u id)/name
其他:
返回路径(名称)
#更改目录
def chdir_笔记本():
d=请求。获取('http://172.28.0.2:9000/api/sessions').json()[0]
文件id=d['path'].split('=')[1]
路径=获取路径(文件id)
nb_dir='/content/drive'/path.parent
os.chdir(nb_dir)
返回nb_dir
现在您只需调用
chdir\u notebook()
,它将更改为该笔记本的原始目录

别忘了先连接你的谷歌硬盘

这里有一个

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

!pip安装kora-q
从可拉进口驱动器
drive.chdir_笔记本()

我早就想自己做这件事,但一直找不到办法。我很想知道是否有人有答案。答案是什么?谢谢你的帮助!我也不确定。它可能是一个在Colab中获取所有Jupyter会话的API。不知怎么的,我在什么地方找到了它(我忘了),但当时我记了下来。