如何在python中从内存中读取(流)来自Google Drive的文件?

时间:2017-08-04 23:47:14

标签: python google-drive-api google-api-python-client

我正在尝试使用google-api-python-client https://google.github.io/google-api-python-client/docs/epy/googleapiclient.http.MediaIoBaseDownload-class.html

读取放在Google云端硬盘上的大型CSV文件

我能够在硬盘上下载文件:

request = drive_service.files().get_media(fileId=file_id)
fh = io.FileIO('test.csv', mode='w')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()

但我想知道是否有一种简单的方法可以在内存中以块的形式读取它。

1 个答案:

答案 0 :(得分:0)

    api_service_object = self.service
    request = api_service_object.files().get_media(fileId=file_id)
    stream = io.BytesIO()
    downloader = MediaIoBaseDownload(stream, request)
    done = False
    # Retry if we received HttpError
    for retry in range(0, 5):
        try:
            while done is False:
                status, done = downloader.next_chunk()
                print "Download %d%%." % int(status.progress() * 100)
            return stream.getvalue()
        except HTTPError as error:
            print 'There was an API error: {}. Try # {} failed.'.format(
                error.response,
                retry,
            )