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

Python调用Google Drive API读取文件时提示未找到文件的问题

问题排查步骤

1. 补充API查询参数

你的代码调用files().list()时未指定关键查询参数,默认仅返回当前认证账号「我的云端硬盘」中的非归档/非回收站文件,可能导致无法匹配目标文件。可补充以下参数:

  • 若目标文件在共享云端硬盘,需添加supportsAllDrives=True和includeItemsFromAllDrives=True
  • 若要排除回收站文件,显式设置trashed=False(默认值,但明确设置可避免歧义)
  • 通过q参数缩小范围,比如仅搜索CSV文件:q="mimeType='text/csv'"

修改后的示例代码:

def search_file(request = None):
    try:
        service = build('drive', 'v3', credentials=creds)

        # 补充参数后的API调用
        results = service.files().list(
            pageSize=1, 
            fields="nextPageToken, files(id, name)",
            supportsAllDrives=True,
            includeItemsFromAllDrives=True,
            q="mimeType='text/csv' and trashed=False"
        ).execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        print(f'An error occurred: {error}')

2. 验证认证账号权限

  • 确认OAuth2认证的账号,是目标CSV文件所在Drive的拥有者或已获得共享权限
  • 若使用服务账号而非个人用户OAuth2认证,需先将服务账号邮箱添加为目标Drive或文件的协作者,否则服务账号无法访问个人Drive文件

3. 检查API权限范围

OAuth2认证流程中,确保请求的权限范围足够:

  • 仅读取元数据用https://www.googleapis.com/auth/drive.metadata.readonly
  • 需读取文件内容用https://www.googleapis.com/auth/drive.readonly或更宽泛的范围
  • 避免权限范围限制导致无法访问目标文件
替代方案

方案1:用PyDrive简化操作

PyDrive封装了Drive API常用操作,代码更简洁:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

# 完成OAuth2认证
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

# 搜索CSV文件
file_list = drive.ListFile({'q': "mimeType='text/csv' and trashed=False"}).GetList()
for file in file_list:
    print(f'{file["title"]} ({file["id"]})')

方案2:直接挂载Google Drive(Jupyter/Colab环境)

在支持挂载的Jupyter环境中,可直接挂载Drive后通过文件路径读取:

from google.colab import drive
drive.mount('/content/drive')

# 读取CSV文件(替换为实际文件路径)
import pandas as pd
df = pd.read_csv('/content/drive/MyDrive/your_target_file.csv')

方案3:服务账号密钥无交互认证

适合需要后台运行的场景,需提前将服务账号添加为文件协作者:

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

# 加载服务账号密钥文件
SERVICE_ACCOUNT_FILE = 'path/to/your/service-account-key.json'
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']

creds = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# 调用Drive API
service = build('drive', 'v3', credentials=creds)
results = service.files().list(
    pageSize=1,
    fields="nextPageToken, files(id, name)",
    supportsAllDrives=True,
    includeItemsFromAllDrives=True
).execute()
# 后续处理逻辑同原代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:25:37