Google Drive给我们提供了很多管理和共享文件的简便方法,而且还是免费的(当然免费账户有一定存储限制)。但是,对于某些edu用户,Google Drive存储不仅是免费的,而且是无配额限制的。您是否想知道如何从数据科学的角度充分利用这种免费的云存储服务? 实际上,这并不困难,我们可以使用Python轻松实现访问和管理Google Drive文件。
设置Google Service API认证
首先,我们需要获取Google Service API的身份验证文件,以便我们的Python代码可以访问Google Drive。 为此,我们需要:
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']))
复制代码
# 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.复制代码
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()
复制代码