筆記 for Python (Google Colab + PyDrive)

Jacky Lu
7 min readMay 13, 2019

--

目錄

  1. 簡介
  2. 語法和範例
  3. 參考資料來源

1. 簡介

Google Colab

  • Google Colab ( Google Colaboratory)是一個以Jupyter Notebook 為開發環境的免費雲端服務
  • 可選擇Python 2 或 Python 3
  • 提供免費的 GPU (K80) 和 TPU (v2)
  • 最長可運行12小時,若閒置過久則會中途自動停止執行
  • 可連結自身Google帳號的雲端硬碟做資料操作

Google Drive

2. 語法和範例

安裝 PyDrive套件

!pip install PyDrive

輸入模組

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

使用者身分驗證

  • 取得
gauth = GoogleAuth()
auth.authenticate_user()
gauth.credentials = GoogleCredentials.get_application_default()
  • 存儲
gauth.SaveCredentialsFile("mycreds.txt")
  • 載入
gauth.LoadCredentialsFile("mycreds.txt")

檔案操作

drive = GoogleDrive(gauth)
  • 建立
# 不指定建立位置,直接建立在drive裡
file1 = drive.CreateFile({'title': 'FILE_NAME_1.txt'})
file1.Upload() # Upload the file.
# 指定建立位置,需要目標資料夾id
file1 = drive.CreateFile({'title': 'FILE_NAME_1.txt',
'parents':[{'kind': 'drive#fileLink',
'id': 'target_folder_id'}]})
file1.Upload() # Upload the file.
# 指定建立位置,需要目標目錄id
# id取得方法會於下方介紹
file1 = drive.CreateFile({'title': 'FILE_NAME_1.txt',
'parents':[{'kind': 'drive#fileLink',
'id': 'target_folder_id'}]})
file1.Upload()
  • 刪除
file1.Trash()  # Move file to trash.
file1.UnTrash() # Move file out of trash.
file1.Delete() # Permanently delete the file.
  • 更新
file1['title'] = 'FILE_NAME_2.txt' # Change title of the file.
file1.Upload() # Update metadata.
  • 查詢
# 不指定建立位置
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
print('title: %s, id: %s' % (file1['title'], file1['id']))
# 指定建立位置
file_list = drive.ListFile({'q': "'target_folder_id' in parents and trashed=false"}).GetList()
for file1 in file_list:
print('title: %s, id: %s' % (file1['title'], file1['id']))

完整範例

  • 身分驗證 - 使用者驗證
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
gauth = GoogleAuth()
auth.authenticate_user()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
  • 身分驗證 - 自動化驗證
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
gauth = GoogleAuth()gauth.LoadCredentialsFile("mycreds.txt")if gauth.credentials is None:
auth.authenticate_user()
gauth.credentials = GoogleCredentials.get_application_default()

elif gauth.access_token_expired:
gauth.Refresh()

else:
gauth.Authorize()
gauth.SaveCredentialsFile("mycreds.txt")drive = GoogleDrive(gauth)
  • 檔案操作 - 取得共用連結
file_list = drive.ListFile({'q': "'1icWmsJmTYsIuMNPBKLdrEh7KXmJJoEoR' in parents and trashed=false"}).GetList()
for file1 in file_list:
print('title: %s, id: %s'
%(file1['title'], file1['webContentLink']))

3. 參考資料來源

--

--