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

Python Google Drive API如何访问共享驱动器内的文件?

解决Google Drive API访问共享目录/驱动器返回空列表的问题

核心原因

当访问**共享驱动器(Shared Drive)**或他人共享的非自身Drive下的目录时,默认的files().list调用不会包含共享驱动器内容;若只是单独共享的目录未挂载到你的Drive中,API也无法直接查询到对应内容。

解决方案步骤

1. 明确共享类型并做前置操作

  • 共享驱动器(团队/组织共享盘):无需挂载到个人Drive,但需确保API凭据拥有该共享盘的访问权限。
  • 他人单独共享的目录:先在网页端Google Drive中操作:右键共享目录 → 「添加到我的云端硬盘」,完成挂载后API才能查询到内容。

2. 修改后的核心查询代码

针对共享场景,添加两个关键参数即可解决空列表问题:

pageToken = ""
dir_id = "<google drive directory id>"
while pageToken is not None:
    query = "'" + dir_id + "' in parents"
    fields = "nextPageToken, files(id, name, mimeType)"
    task = self.drive.files().list(
        q=query,
        pageSize=1000,
        pageToken=pageToken,
        fields=fields,
        # 关键新增参数:启用共享驱动器访问支持
        includeItemsFromAllDrives=True,
        supportsAllDrives=True
    )
    response = task.execute()
    pageToken = response.get('nextPageToken')
    # 遍历返回的文件列表
    for file in response.get('files', []):
        print(f"文件名称: {file['name']}, ID: {file['id']}")

3. 权限与参数验证

  • 确认API凭据(OAuth2令牌或服务账号)已被共享者添加为资源协作者,至少拥有查看权限。
  • 若访问共享驱动器的根目录,需确保dir_id是共享驱动器的根目录ID(可通过网页端共享盘URL获取,或调用drive.drives().get(driveId='<共享驱动器ID>')接口获取根目录ID)。

4. 共享文件下载补充代码

下载共享文件时同样需要添加supportsAllDrives=True参数:

from googleapiclient.http import MediaIoBaseDownload

def download_shared_file(drive_service, file_id, save_path):
    request = drive_service.files().get_media(fileId=file_id, supportsAllDrives=True)
    with open(save_path, 'wb') as f:
        downloader = MediaIoBaseDownload(f, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(f"下载进度: {int(status.progress() * 100)}%")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:15:29