You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.10环境下从Google Drive下载文件的可行方案

Python 3.10环境下从Google Drive下载文件的可行方法

方法一:使用Google Drive官方API(支持所有文件类型,需授权)

适用于访问私有文件或批量下载的场景,官方API完全兼容Python 3.10版本。

  • 先安装依赖包:
    pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
  • 操作步骤与代码示例:
  1. 前往Google Cloud控制台创建项目,启用Google Drive API,下载credentials.json文件到本地项目目录。
  2. 运行以下代码(替换对应参数):
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import io

# 只读权限范围,如需修改可调整
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']

def download_file_from_drive(file_id, save_path):
    creds = None
    # 加载已保存的授权token(如果存在)
    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)
        # 保存token供后续使用
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    # 初始化Drive服务
    service = build('drive', 'v3', credentials=creds)

    # 发起文件下载请求
    request = service.files().get_media(fileId=file_id)
    fh = io.FileIO(save_path, 'wb')
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print(f"下载进度: {int(status.progress() * 100)}%")

# 替换为你的文件ID和保存路径
download_file_from_drive('你的文件ID', '保存的文件名.后缀')

注:文件ID可从Google Drive文件链接中提取,例如https://drive.google.com/file/d/1XyzAbc123/view中的1XyzAbc123就是文件ID。

方法二:使用requests下载公开共享文件(无需授权,仅适用于公开文件)

如果文件设置为“任何人可查看”的公开权限,无需复杂授权,直接用requests即可下载:

  • 先安装requests:
    pip install requests
  • 代码示例:
import requests

def download_public_drive_file(file_id, save_path):
    base_url = f"https://drive.google.com/uc?export=download&id={file_id}"
    session = requests.Session()

    response = session.get(base_url, stream=True)
    # 处理大文件的确认页面
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            base_url = f"https://drive.google.com/uc?export=download&confirm={value}&id={file_id}"
            response = session.get(base_url, stream=True)
            break

    # 分块写入文件
    with open(save_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=32768):
            if chunk:
                f.write(chunk)

# 替换为公开文件的ID和保存路径
download_public_drive_file('你的公开文件ID', '保存的文件名.后缀')

内容的提问来源于stack exchange,提问作者PeeteKeesel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:40:24