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

2024-04-24 15:43:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从我的google驱动器下载一个文件,在用python做了一些测试之后,我得到了从驱动器下载的数据,就像google文档所说的(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))

这是我代码的结果

API DRIVE


Tags: fromhttpsimportcomtokenauthifgoogle
2条回答
  • 您想将下载的文件另存为本地PC的文件
  • 您希望通过使用带有python的googleapi python客户端来实现这一点。你知道吗
  • 您已经能够使用驱动器API获取和放置文件。你知道吗

如果我的理解是正确的,这个修改怎么样?你知道吗

发件人:

fh = io.BytesIO()

收件人:

fh = io.FileIO("### filename ###", mode='wb')

参考文献:

如果这不是你想要的结果,我道歉。你知道吗

在github上安装gshell,非常有用

相关问题 更多 >