歡迎訂閱微信公衆號和YouTube頻道:html
Google Drive給咱們提供了不少管理和共享文件的簡便方法,並且仍是免費的(固然免費帳戶有必定存儲限制)。可是,對於某些edu用戶,Google Drive存儲不只是免費的,並且是無配額限制的。您是否想知道如何從數據科學的角度充分利用這種免費的雲存儲服務? 實際上,這並不困難,咱們可使用Python輕鬆實現訪問和管理Google Drive文件。python
首先,咱們須要獲取Google Service API的身份驗證文件,以便咱們的Python代碼能夠訪問Google Drive。 爲此,咱們須要:json
在Google Developer Console 頁面創建一個新項目(以下圖所示) api
點擊"ENABLE APIS AND SERVICES"開通API服務(以下圖所示). 瀏覽器
點擊"CREATE CREDENTIALS"建立密碼信息。 微信
下面咱們就能夠經過在終端運行pip install pydrive
安裝PyDrive庫,並使用PyDrive庫管理和讀寫Google Drive文件。學習
下面的代碼將完成Google Drive用戶認證,並列出Google Drive根目錄下的全部文件。須要說明的是,咱們須要把上面步驟中下載的JSON文件另存爲client_serets.json
文件,並把它放到Python程序所在的存儲文件下。網站
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
# Rename the downloaded JSON file to client_secrets.json
# The client_secrets.json file needs to be in the same directory as the script.
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
# List files in Google Drive
fileList = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
print('title: %s, id: %s' % (file1['title'], file1['id']))
複製代碼
每次運行上面的代碼,程序都會自動打開一個瀏覽器頁面讓用戶填寫Google用戶名和密碼。爲了不每次都填寫用戶名和密碼,咱們能夠建立一個settings.yaml
文件,以下所示完成相關設置。settings.yaml
文件的具體信息可參見PyDrive官方文檔。this
client_config_backend: settings
client_config:
client_id: your_client_id
client_secret: your_client_secret
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
get_refresh_token: True
oauth_scope:
- https://www.googleapis.com/auth/drive.file
複製代碼
其中, client_id
和client_secret
能夠經過下面所示的截圖得到。 google
credientials.json
文件。 再次運行時,Python會自動提取該文件中的內容完成身份驗證,這樣咱們就不須要再次輸入密碼了。
利用下面的代碼,咱們就能夠把本地文件上傳到Google Drive指定的文件夾裏。
# Upload files to your Google Drive
upload_file_list = ['google_console1.png', 'google_console2.png']
for upload_file in upload_file_list:
gfile = drive.CreateFile({'parents': [{'id': '1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t'}]})
# Read file and set it as a content of this instance.
gfile.SetContentFile(upload_file)
gfile.Upload() # Upload the file.
複製代碼
上面的代碼將兩個本地文件google_console1.png
和google_console2.png
上傳到個人Google Drive文件夾test/
中。 爲此,PyDrive庫將在Google Drive中建立兩個文件,而後讀取並將本地的兩個文件上傳到相應的文件中。 此處,咱們須要提供相應Google Drive文件夾的id
。 在此示例中,test
文件夾的ID爲1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t
。 小竅門:咱們能夠從瀏覽器中獲取Google Drive文件夾ID。 例如,當我在Google Drive中打開test
文件夾時,瀏覽器將地址顯示爲https://drive.google.com/drive/folders/1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t
。test
文件夾的相應ID是瀏覽器地址欄中最後一個\
符號後的部分,即1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t
。
一樣,咱們也可使用如下代碼直接將文件寫入Google Drive:
file1 = drive.CreateFile({
'parents': [{'id': '1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t'}],
'title': 'Hello.txt'}) # Create GoogleDriveFile instance with title 'Hello.txt'.
file1.SetContentString('Hello World!') # Set content of the file from given string.
file1.Upload()
複製代碼
咱們也能夠用下面的代碼直接讀取Google Drive裏的文件。
file2 = drive.CreateFile({'id': file1['id']})
file2.GetContentString('Hello.txt')
複製代碼
經過這篇文章,咱們學習瞭如何使用PyDrive直接管理Google Drive中的文件(包括讀寫和建立)。 主要步驟以下:
歡迎訂閱微信公衆號和YouTube頻道: