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

使用Google服务账号调用Drive API查询文件夹内容返回无文件

问题原因与修复方案

你的代码核心问题出在查询语句的逻辑优先级错误以及**parents in的语法不正确**,导致筛选条件没有按预期生效。

具体问题分析

  1. 逻辑运算符优先级问题:and的优先级高于or,原查询语句会被解析为:

    (mimeType='folder') or (mimeType='document') or (mimeType='spreadsheet') or (mimeType='presentation' and trashed=false and parents='xxx')
    

    这意味着只有Google幻灯片类型的文件会应用「不在回收站」和「属于目标文件夹」的条件,其他类型的文件完全忽略这两个限制,自然无法正确筛选出目标文件夹内的内容。

  2. parents in语法错误:parents in后面需要跟数组格式的文件夹ID,而不是单个字符串,正确写法是parents in ['16x7o7CNCscM-lFqnKaXwUf1Bv-OTQK0W']。

修正后的代码

import logging
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

creds = Credentials.from_service_account_file('bayfiles-779393795f34.json', scopes=['https://www.googleapis.com/auth/drive'])

service = build('drive', 'v3', credentials=creds)

# 修复逻辑分组和parents语法
query = "(mimeType='application/vnd.google-apps.folder' or mimeType='application/vnd.google-apps.document' or mimeType='application/vnd.google-apps.spreadsheet' or mimeType='application/vnd.google-apps.presentation') and trashed = false and parents in ['16x7o7CNCscM-lFqnKaXwUf1Bv-OTQK0W']"

# 添加pageSize确保返回所有结果(默认最多100条,可根据需求调整)
results = service.files().list(q=query, pageSize=1000).execute()
items = results.get("files", [])

if not items:
    logger.debug("No files found")
else:
    # Print file names
    for item in items:
        logger.debug(f'The service account has access to the file "{item["name"]}" with ID "{item["id"]}"')

额外验证步骤

  • 确认服务账号邮箱已被添加到temp2文件夹的权限列表中,且权限级别至少为查看者(建议用编辑权限避免权限不足)。
  • 核对代码中使用的文件夹ID是否与temp2文件夹的实际ID完全一致(可从文件夹URL的最后一段获取)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:50:20