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

如何通过Google Drive API区分文件与文件夹(Python实现)

区分Google Drive API返回的文件与文件夹的正确方法

你之前通过size或sha256Checksum字段判断的方式不可靠——像Google Docs、Sheets这类云端原生文件,也不会返回这两个字段,但它们属于文件而非文件夹。正确的方式是通过MIME类型判断,这是Google Drive API官方规定的标准区分方法。

步骤1:修改API请求,获取mimeType字段

在你的files().list请求中,需要在fields参数里加上mimeType,让返回的每个条目都包含类型信息:

results = service.files().list(
    pageSize=1000, 
    fields="nextPageToken, files(kind, id, name, size, parents, sha256Checksum, version, modifiedTime, mimeType)"
).execute()
items = results.get('files', [])

步骤2:通过MIME类型判断文件/文件夹

Google Drive中文件夹的MIME类型固定为application/vnd.google-apps.folder,遍历返回条目时,只需检查这个字段即可:

for item in items:
    # 判断是否为文件夹
    if item.get('mimeType') == 'application/vnd.google-apps.folder':
        print(f"[文件夹] 名称: {item['name']}, ID: {item['id']}")
    else:
        print(f"[文件] 名称: {item['name']}, ID: {item['id']}")

补充:常见Google原生文件的MIME类型(可选)

如果需要细分文件类型,以下是部分常见的Google云端文件MIME类型:

  • Google Docs: application/vnd.google-apps.document
  • Google Sheets: application/vnd.google-apps.spreadsheet
  • Google Slides: application/vnd.google-apps.presentation

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:42:43