使用Python 3.10从Google Drive下载文件



我正在使用python 3.10.5,想知道如何从Google Drive下载文件

?我在这里找到了一些答案,比如使用gdown。但是,对于我的python版本,不支持gdown。

是否有人有使用python 3.10下载谷歌驱动器文件的工作方式?

下载带有Drive 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 Drive。

引用:

https://developers.google.com/drive/api/quickstart/python
  • https://developers.google.com/drive/api/guides/manage-downloads python

最新更新