我正在使用python 3.10.5,想知道如何从Google Drive下载文件?我找到了一些答案,比如在here中使用gdown。但是,对于我的python版本,gdown不受支持。有没有人有一个工作方式下载谷歌驱动器文件使用python 3.10?
uqdfh47h1#
使用驱动器API下载文件。
应该可以利用Python官方文档中的示例来下载文件。我有一个基于它的代码,允许我下载图像:
from __future__ import print_function import os.path import requests import io from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload from googleapiclient.http import MediaIoBaseDownload # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive'] def creds(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) 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) with open('token.json', 'w') as token: token.write(creds.to_json()) return creds def download(creds, real_file_id): try: # create drive api client service = build('drive', 'v3', credentials=creds) file_id = real_file_id # pylint: disable=maybe-no-member request = service.files().get_media(fileId=file_id) file = io.BytesIO() downloader = MediaIoBaseDownload(file, request) done = False while done is False: status, done = downloader.next_chunk() print(F'Download {int(status.progress() * 100)}.') except HttpError as error: print(F'An error occurred: {error}') return file.getvalue() if __name__ == '__main__': file = open("test.jpg","wb") file.write(download(creds(), "ID of the Image"))
您只需要拥有要下载的文件的ID,并将其粘贴到示例代码的末尾进行测试。确保已创建凭据并按照快速入门流程在Python下安装Google云端硬盘。
参考资料:
1条答案
按热度按时间uqdfh47h1#
使用驱动器API下载文件。
应该可以利用Python官方文档中的示例来下载文件。我有一个基于它的代码,允许我下载图像:
您只需要拥有要下载的文件的ID,并将其粘贴到示例代码的末尾进行测试。
确保已创建凭据并按照快速入门流程在Python下安装Google云端硬盘。
参考资料: