问题
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.
This is the code I have:
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')
Just to reiterate I would like to download a few csv files and then proceed to read the files.
回答1:
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.
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).
A binary file can be downloaded by adding alt=media
to the URL.
A Google file can be exported by adding /export?mimeType=text/csv
to the URL.
See https://developers.google.com/drive/api/v3/manage-downloads for details and code samples.
来源:https://stackoverflow.com/questions/55261031/troubles-downloading-csv-files-from-google-drive