从Google云端硬盘下载csv文件时遇到麻烦

问题描述 投票:0回答:1

我想我无法理解我做错了什么。我已连接到Google Drive API,现在我想在我的Google驱动器上阅读一些文档,目的是分析这些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文件,然后继续阅读文件。

python google-api google-drive-sdk google-api-python-client
1个回答
1
投票

在Drive中,文件的元数据与其内容是分开的。您已经要求使用metadata.readonly范围,这不足为奇,只允许访问元数据。您对files().get的调用然后获取元数据。

要获取内容,首先需要选择更宽松的范围。然后你将获取内容。如何执行此操作取决于文件是二进制文件还是Google文档(例如电子表格)。

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

可以通过将/export?mimeType=text/csv添加到网址来导出Google文件。

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

© www.soinside.com 2019 - 2024. All rights reserved.