问题描述
我认为我无法理解我在做错什么.我已经连接到Google Drive API,现在我想阅读我的Google Drive上的一些文档,目的是分析这些csv文件中包含的数据.
I think i'm failing to understand what i'm doing wrong. I have connected to the Google Drive API and now I would like to read a few documents on my Google drive with the objective of analysing the data contained in these csv files.
这是我的代码:
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文件,然后继续读取文件.
Just to reiterate I would like to download a few csv files and then proceed to read the files.
推荐答案
在云端硬盘中,文件的元数据与其内容分开.您已要求metadata.readonly
范围,这毫不奇怪地仅允许访问元数据.您对files().get
的调用将获取元数据.
In Drive, a File's metadata is separate from its content. You have asked for metadata.readonly
scope, which unsurprisingly only allows access to the metadata. Your call to files().get
then gets the metadata.
要获取内容,您首先需要选择一个更宽松的范围.然后,您将获取内容.具体操作方式取决于文件是二进制文件还是Google文档(例如电子表格).
To get the content, you will firstly need to choose a more permissive scope. Then you will fetch the content. How you do this depends on whether the file is a binary file, or a Google document (eg. a spreadsheet).
可以通过将alt=media
添加到URL来下载二进制文件.
A binary file can be downloaded by adding alt=media
to the URL.
可以通过在URL中添加/export?mimeType=text/csv
来导出Google文件.
A Google file can be exported by adding /export?mimeType=text/csv
to the URL.
请参见 https://developers.google.com/drive/api/v3/manage-downloads 以获得详细信息和代码示例.
See https://developers.google.com/drive/api/v3/manage-downloads for details and code samples.
这篇关于麻烦从Google云端硬盘下载csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!