衆所周知,Google Colab是Google提供的運行在雲端的jupyter notebook環境。裏面集成了許多著名的機器學習python庫。由於這個環境是運行在Google虛擬機上的,顯然與自己的PC不在一個文件系統。那麼怎麼與我們自己的文件交互呢?
Colab文檔裏提供了四種方式,分別是:
- 從本地直接上傳
- 連接Google Drive
- 連接Google Sheet
- 連接Google Cloud Storage
下面就來分別描述。
1.與本地文件交互
從本地直接上傳
files.upload() 返回一個由我們上傳的所有文件構成的一個字典。 這個字典的key是文件名, 這個字典的value是我們上傳的文件的data。
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))
從Colab下載文件到本地
from google.colab import files
with open('example.txt', 'w') as f:
f.write('some content')
files.download('example.txt')
2.連接Google Drive
這裏官方有提供了許多種方法。這裏我就挑一種介紹了,有興趣的可以點進這個鏈接進去看。
這裏只介紹使用PyDrive的方法。PyDrive是google-api-python-client的包裝庫,簡化了許多常見的Google Drive API任務。
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# 1. 驗證身份並創建pydrive客戶端.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# PyDrive 參考:
# https://gsuitedevs.github.io/PyDrive/docs/build/html/index.html
# 2. 創建並上傳一個文本文檔.
uploaded = drive.CreateFile({'title': 'Sample upload.txt'})
uploaded.SetContentString('Sample upload file content')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))
# 3. 通過id訪問文件並輸出它的內容.
downloaded = drive.CreateFile({'id': uploaded.get('id')})
print('Downloaded content "{}"'.format(downloaded.GetContentString()))