筆記 for Python (Google Colab + PyDrive)

  1. 語法和範例
  2. 參考資料來源
  • 可選擇Python 2 或 Python 3
  • 提供免費的 GPU (K80) 和 TPU (v2)
  • 最長可運行12小時,若閒置過久則會中途自動停止執行
  • 可連結自身Google帳號的雲端硬碟做資料操作

安裝 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']))

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store