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

标签 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))

这是我的代码的结果

API DRIVE

最佳答案

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

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

来自:

fh = io.BytesIO()

致:

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

引用文献:

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

关于python - 如何将从 Google Drive 下载的数据保存在文件中 - Python Drive API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57383359/

相关文章:

python - 使用flask-sqlqcodegen 为 Flask-AppBuilder 生成模型

python - 如何提高 django mysql 复制性能?

python - Tensorflow:多项尝试中结果的概率

python - Python 按月和年计算多个列值的平均值

oauth - Drive API 的 Google API OAuth 不起作用。获取错误 : origin_mismatch

php - 使用 google-drive-api 创建一个子文件夹并使用 PHP 返回 id

python - 我为 Neo4j 做的 Python 对象映射是否太天真了?

python - 如何实现用于测试的内存密集型 python 脚本

python - 属性错误: '_mysql.connection' object has no attribute 'cursor'

javascript - 使用javascript从谷歌驱动器文件夹中获取图片到我的网站