📅  最后修改于: 2023-12-03 15:06:31.290000             🧑  作者: Mango
如果你需要从 Google Drive 下载大量文件或文件夹,而不想在本地打开浏览器并一个一个下载,可能需要了解如何在命令行中下载。
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import io
from googleapiclient.http import MediaIoBaseDownload
# 从谷歌云盘上下载文件
def download_file(file_id, local_path, creds):
try:
service = build('drive', 'v3', credentials=creds)
file = service.files().get(fileId=file_id).execute()
filename = file['name']
# 将文件下载到内存中
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print(f"Download {int(status.progress() * 100)}.")
# 将内存中的文件写入磁盘
with open(f"{local_path}/{filename}", 'wb') as f:
f.write(fh.getbuffer())
except HttpError as error:
print(f'An error has occurred: {error}')
raise error
# 运行下载函数
creds = Credentials.from_authorized_user_file('path/to/credentials.json') # 替换为自己的密钥文件路径
download_file('1pZ08ecA8Xctf_ghjJ47ZXv7MVu2_gnmg', 'path/to/local/download/folder', creds) # 替换为自己的文件 ID 和本地路径
python download.py
使用 Google API client 和 Python,可以轻松在命令行中从 Google Drive 下载大量文件和文件夹。通过 OAuth 2.0,以及 Google API client 的下载功能,可以轻松地下载文件到内存中,然后将其写入磁盘。