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

使用gspread打开谷歌表格出现KeyError: 'access_token'错误如何解决

错误原因排查与修复方案

1. 直接错误原因:Scope地址拼写错误

你代码中定义的scope列表里存在拼写错误:
原错误代码的scope项:

'https://www.googleapis.com/auth/spreadheets'

这里少写了一个s,正确的地址应为:

'https://www.googleapis.com/auth/spreadsheets'

这个拼写错误导致权限校验时无法获取正确的访问令牌,直接触发KeyError: 'access_token'以及后续的刷新错误。

2. 修复后的完整代码

你使用的oauth2client库已经停止维护,建议替换为谷歌官方维护的google-auth系列库,修复步骤如下:
首先安装依赖:

pip install gspread google-auth

代码部分:

import gspread
from google.oauth2.service_account import Credentials

scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/drive"
]

creds = Credentials.from_service_account_file("C:/Users/jadot/PycharmProjects/multiplicationTable/creds.json", scopes=scope)

client = gspread.authorize(creds)

sheet = client.open("multiplicationTable").sheet1

3. 其他需要检查的配置项

如果修改后仍报错,请逐一确认以下配置:

  • Google Cloud控制台中已经同时启用「Google Sheets API」和「Google Drive API」
  • 打开你要访问的multiplicationTable谷歌表格,点击右上角「共享」,将creds.json文件中client_email字段对应的邮箱地址添加为协作者,分配编辑权限
  • 确认creds.json的文件路径正确,无拼写或读取权限问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:24:09