如何将从 Google Drive 下载的数据保存在文件中 - Python Drive API

dav*_*009 2 python python-3.x google-drive-api

我需要从我的谷歌驱动器下载一个文件,在使用 python 进行一些测试后,我从驱动器下载了数据,就像谷歌文档所说的那样https://developers.google.com/drive/api/v3/quickstart/python), (https://developers.google.com/drive/api/v3/manage-downloads#downloading_a_file),但我不知道如何将此“数据”保存在文件

我怎样才能做到这一点?

这是我的代码

from __future__ import print_function
import pickle
import os.path
import io
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload

SCOPES = ['https://www.googleapis.com/auth/drive']

creds = None

if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('drive', 'v3', credentials=creds)

file_id = '1ZR7MpJe9KQliuICCv-5iae6DeGQzHaTB'
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print(status)
    print ("Download %d%%." % int(status.progress() * 100))

Run Code Online (Sandbox Code Playgroud)

这是我的代码的结果

API驱动

Tan*_*ike 6

  • 您想将下载的文件作为文件保存到本地PC。
  • 您希望使用 google-api-python-client 和 Python 来实现此目的。
  • 您已经能够使用 Drive API 获取和放置文件。

如果我的理解是正确的,那么这个修改怎么样?

从:

fh = io.BytesIO()
Run Code Online (Sandbox Code Playgroud)

到:

fh = io.FileIO("### filename ###", mode='wb')
Run Code Online (Sandbox Code Playgroud)

参考:

如果这不是您想要的结果,我深表歉意。