背景
Google Drive給我們提供了很多管理和共享文件的簡便方法,而且還是免費的(當然免費賬戶有一定存儲限制)。但是,對于某些edu用戶,Google Drive存儲不僅是免費的,而且是無配額限制的。您是否想知道如何從數據科學的角度充分利用這種免費的云存儲服務? 實際上,這并不困難,我們可以使用Python輕松實現訪問和管理Google Drive文件。
設置Google Service API認證
首先,我們需要獲取Google Service API的身份驗證文件,以便我們的Python代碼可以訪問Google Drive。 為此,我們需要:
在Google Developer Console 頁面建立一個新項目(如下圖所示)
你可以給這個項目一個名字,也可以設為默認值。
點擊”ENABLE APIS AND SERVICES”開通API服務(如下圖所示).
然后頁面會轉到下面的截圖。
在上面的搜索框內搜索”Google Drive”,我們會得到如下界面。
點擊”Google Drive API”,進入下一個界面。
點擊”ENABLE”開通Google Drive API服務,進入下一個界面。
點擊”CREATE CREDENTIALS”創建密碼信息。
在上面的截圖中點擊”client ID”,然后在下一個界面中點擊”CREATE”,并下載創建成功的JSON密碼文件如下。
下載的JSON文件就是Python程序讀寫Google Drive所需要的Google Serivces認證文件。
安裝使用PyDrive
下面我們就可以通過在終端運行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官方文檔。
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可以通過下面所示的截圖獲得。
重新運行上面的Python代碼,程序將要求您再次輸入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中的文件(包括讀寫和創建)。 主要步驟如下:
設置Google DriveAPI并創建認證文件
安裝PyDrive并完成身份驗證
使用Python管理Google Drive文件(比如上傳和讀寫)
更多PyDrive的使用和文件管理功能請參見PyDrive官方網站。