首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python:如何使用api从Google drive下载文件

python:如何使用api从Google drive下载文件
EN

Stack Overflow用户
提问于 2015-02-04 04:51:05
回答 2查看 13.5K关注 0票数 6

我想使用google drive api将google drive中的文件下载到我的系统中。我如何实现这一点?

根据https://developers.google.com/drive/v2/reference/files/get#examples给出的例子

代码语言:javascript
复制
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

我可以找到该文件,但如何将其本地下载到我的计算机上?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-04 23:09:39

只需将内容变量写入文件,而不是返回内容

代码语言:javascript
复制
fo = open("foo.jpg", "wb")
fo.write(content)
fo.close()
票数 3
EN

Stack Overflow用户

发布于 2016-12-21 21:00:59

我觉得你应该看看这个:

http://pythonhosted.org/PyDrive/

代码看起来更简单

代码语言:javascript
复制
# 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"}'
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28308489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档