colab 读入 google drive 的文件

近段时间需要使用google colab训练一些神经网络,但是colab默认是不能读入google drive的数据的,每次都要重新上传,费时费力。所以这篇博客是让colab用户能够使用google drive的工作文件夹

2018年12月亲测有效。

step1

首先需要让colab获得google drive的授权,在google colab里执行如下代码:

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

执行时会打印一个网址和一个授权码的输入框,此时你需要点击网址,登陆google account,授权colab使用你的google drive,然后系统会分配给你一个授权码,你需要将授权码粘贴到输入框里,回车继续。

若打印出success的信息,说明授权成功。

step 2

执行如下代码:

# 指定Google Drive云端硬盘的根目录,名为drive
!mkdir -p drive
!google-drive-ocamlfuse drive

此时colab中出现drive的文件夹,里面就是你的google drive的根目录文件

step3

然后更换执行的工作文件夹即可。

import os
os.chdir("drive/Colab Notebooks") 

你可能感兴趣的:(colab 读入 google drive 的文件)