colab支持自己上传文件,但是每隔一段时间就会被清空,所以最好使用是配合google drive使用,避免了资源的重复上传*
第一步给colab授权google drive的使用
在google drive中选择一个notebook打开,作为工作路径
然后再在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账号,然后将验证码复制进入窗口即可。
第二步 指定Google Drive云端硬盘的根目录,名为drive
!mkdir -p drive
!google-drive-ocamlfuse drive
colab中就能看到挂载上去的google drive了
效果图:
第三步 如果需要导入其他目录下的文件
import sys
sys.path.insert(0, '/content/drive')
sys.path是个列表,所以在末尾添加目录是很容易的,用sys.path.append就行了。当这个append执行完之后,新目录即时起效,以后的每次import操作都可能会检查这个目录。如同解决方案所示,可以选择用sys.path.insert(0,…,这样新添加的目录会优先于其他目录被import检查