python:如何使用 api 从 Google 驱动器下载文件
python: How do i download a file from Google drive using api
我想使用 google 驱动器 api 将 google 驱动器中的文件下载到我的系统。我该如何实施?
根据 https://developers.google.com/drive/v2/reference/files/get#examples
中给出的示例
def print_file(service, file_id):
"""Print a file's metadata.
Args:
service: Drive API service instance.
file_id: ID of the file to print metadata for.
"""
try:
file = service.files().get(fileId=file_id).execute()
print 'Title: %s' % file['title']
print 'MIME type: %s' % file['mimeType']
except errors.HttpError, error:
print 'An error occurred: %s' % error
def download_file(service, drive_file):
"""Download a file's content.
Args:
service: Drive API service instance.
drive_file: Drive File instance.
Returns:
File's content if successful, None otherwise.
"""
download_url = drive_file.get('downloadUrl')
if download_url:
resp, content = service._http.request(download_url)
if resp.status == 200:
print 'Status: %s' % resp
return content
else:
print 'An error occurred: %s' % resp
我能够找到该文件,但我如何才能将它下载到我的本地机器上?
只需将内容变量写入文件而不是返回内容
fo = open("foo.jpg", "wb")
fo.write(content)
fo.close()
我想你应该看看这个:
http://pythonhosted.org/PyDrive/
代码好像更简单
# Initialize GoogleDriveFile instance with file id.
file6 = drive.CreateFile({'id': file5['id']})
file6.GetContentFile('catlove.png') # Download file as 'catlove.png'.
# Initialize GoogleDriveFile instance with file id.
file7 = drive.CreateFile({'id': file4['id']})
content = file7.GetContentString()
# content: '{"firstname": "Claudio", "lastname": "Afshar"}'
我想使用 google 驱动器 api 将 google 驱动器中的文件下载到我的系统。我该如何实施?
根据 https://developers.google.com/drive/v2/reference/files/get#examples
中给出的示例def print_file(service, file_id):
"""Print a file's metadata.
Args:
service: Drive API service instance.
file_id: ID of the file to print metadata for.
"""
try:
file = service.files().get(fileId=file_id).execute()
print 'Title: %s' % file['title']
print 'MIME type: %s' % file['mimeType']
except errors.HttpError, error:
print 'An error occurred: %s' % error
def download_file(service, drive_file):
"""Download a file's content.
Args:
service: Drive API service instance.
drive_file: Drive File instance.
Returns:
File's content if successful, None otherwise.
"""
download_url = drive_file.get('downloadUrl')
if download_url:
resp, content = service._http.request(download_url)
if resp.status == 200:
print 'Status: %s' % resp
return content
else:
print 'An error occurred: %s' % resp
我能够找到该文件,但我如何才能将它下载到我的本地机器上?
只需将内容变量写入文件而不是返回内容
fo = open("foo.jpg", "wb")
fo.write(content)
fo.close()
我想你应该看看这个:
http://pythonhosted.org/PyDrive/
代码好像更简单
# Initialize GoogleDriveFile instance with file id.
file6 = drive.CreateFile({'id': file5['id']})
file6.GetContentFile('catlove.png') # Download file as 'catlove.png'.
# Initialize GoogleDriveFile instance with file id.
file7 = drive.CreateFile({'id': file4['id']})
content = file7.GetContentString()
# content: '{"firstname": "Claudio", "lastname": "Afshar"}'