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

如何获取Google Drive目录文件ID列表并下载指定文件夹内的文件

报错原因

ListFile是第三方库PyDrive的方法,你当前使用的是Google官方google-api-python-client库构建的Drive v3服务,不存在该方法,因此抛出属性不存在的报错。
另外你的原有代码存在缩进错误:service = make_conect()写在了user_video_direct函数的return语句之后,永远不会执行,需要将这行代码移到全局作用域,在调用文件查询接口之前执行。

修复代码

1. 正确获取指定文件夹内所有文件信息

# 初始化Drive服务
service = make_conect()
if not service:
    raise Exception("Drive服务初始化失败")

# 目标文件夹ID
TARGET_FOLDER_ID = "1R6eT6NE19_9LshSK3FsIHMVY6KOkhrG2"

# 调用官方Drive v3接口查询文件列表
resp = service.files().list(
    q = f"'{TARGET_FOLDER_ID}' in parents and trashed = false", # 筛选当前文件夹下未被删除的文件
    fields = "files(id, name, mimeType)", # 按需指定返回字段
    pageSize = 1000 # 单页最大返回1000条,文件数超过该值需自行处理分页逻辑
).execute()

file_list = resp.get("files", [])
# 打印所有文件信息
for file in file_list:
    print(f"文件名:{file['name']} | 文件ID:{file['id']} | 文件类型:{file['mimeType']}")

2. 批量下载文件

import io
from googleapiclient.http import MediaIoBaseDownload

def download_single_file(service, file_id, save_dir="./"):
    # 获取文件元信息
    file_meta = service.files().get(fileId=file_id, fields="name, mimeType").execute()
    file_name = file_meta["name"]
    mime_type = file_meta["mimeType"]
    save_path = save_dir + file_name

    # 区分谷歌文档类文件和普通二进制文件处理
    if mime_type.startswith("application/vnd.google-apps"):
        # 谷歌文档类文件需要先导出为可下载格式,可按需调整导出映射
        export_map = {
            "application/vnd.google-apps.document": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "application/vnd.google-apps.spreadsheet": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "application/vnd.google-apps.presentation": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
        }
        request = service.files().export_media(fileId=file_id, mimeType=export_map.get(mime_type, "application/pdf"))
        # 导出的docx/xlsx等文件需要补充后缀
        if "document" in mime_type:
            save_path += ".docx"
        elif "spreadsheet" in mime_type:
            save_path += ".xlsx"
        elif "presentation" in mime_type:
            save_path += ".pptx"
        else:
            save_path += ".pdf"
    else:
        # 普通二进制文件直接下载
        request = service.files().get_media(fileId=file_id)

    # 写入本地文件
    with io.FileIO(save_path, "wb") as f:
        downloader = MediaIoBaseDownload(f, request)
        done = False
        while not done:
            status, done = downloader.next_chunk()
            print(f"{file_name} 下载进度:{int(status.progress()*100)}%")
    print(f"{file_name} 下载完成,保存路径:{save_path}")

# 批量调用下载
for file in file_list:
    download_single_file(service, file["id"])
注意事项
  • 如果文件夹内文件超过1000个,需要通过接口返回的nextPageToken循环拉取所有文件
  • 下载大文件时可调整MediaIoBaseDownload的分片大小,避免请求超时

内容的提问来源于stack exchange,提问作者данила соловьев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:57:02