【问题标题】:Troubles downloading csv files from Google Drive从 Google 云端硬盘下载 csv 文件时遇到问题
【发布时间】:2019-03-20 12:41:10
【问题描述】:

我想我没能理解我做错了什么。我已连接到 Google Drive API,现在我想阅读我的 Google Drive 上的一些文档,目的是分析这些 csv 文件中包含的数据。

这是我的代码:

from __future__ import print_function
import pickle
import os.path
from httplib2 import Http
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/emmanuelsibanda/credentials.json"
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
creds = None
if os.path.exists('token.pickle'):
  with open('token.pickle', 'rb') as token:
    creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    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()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

def gdrive_download(file_id):
  request = service.files().get(fileId=file_id)
  return request.execute()
a = gdrive_download('19sPsANUblhXkb3nZVy4PMrfUyOSoF_uQ')

重申一下,我想下载一些 csv 文件,然后继续阅读这些文件。

【问题讨论】:

  • 显示你的错误
  • 你现在的代码有什么问题?
  • 我猜我的困惑是读取文件中的数据。据我所知,我只有文件的 ID、文件名等,但没有文件的实际内容

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


【解决方案1】:

在云端硬盘中,文件的元数据与其内容是分开的。您要求metadata.readonly 范围,不出所料,它只允许访问元数据。您对files().get 的调用将获取元数据。

要获取内容,您首先需要选择一个更宽松的范围。然后您将获取内容。具体操作方式取决于文件是二进制文件还是 Google 文档(例如电子表格)。

可以通过在 URL 中添加alt=media 来下载二进制文件。

可以通过在 URL 中添加 /export?mimeType=text/csv 来导出 Google 文件。

有关详细信息和代码示例,请参阅https://developers.google.com/drive/api/v3/manage-downloads

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多