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

Python写入Google Sheet时遇SpreadsheetNotFound错误的排查与解决

Google Sheets Python 脚本报错及解决方案

环境信息

  • 操作系统:Windows 11
  • Python版本:3.11
  • 开发工具:VS Code

需求

通过Python脚本批量填充Google表格单元格,编写了用于验证表格访问及写入权限的代码。

初始代码

# 用于写入Google Sheets
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import json

scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]

credentials = ServiceAccountCredentials.from_json_keyfile_name("[filename].json", scopes) 
file = gspread.authorize(credentials) 
sheet = file.open("[spreadsheetName]") 
sheet = sheet.testSheet 

报错信息

Traceback (most recent call last):
File "[pythonScriptPath]", line 15, in 
sheet = file.open("[spreadsheetName]")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "[anotherPath]", line 160, in open
raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound

已做排查

已将目标表格共享给JSON文件中的服务账号邮箱(后缀为iam.gserviceaccount.com)并设置编辑权限,且JSON文件与脚本处于同一目录,但问题未解决。

解决代码

参考gspread官方文档修改代码后问题解决,修改后的代码如下(WORKSHEET_NAME为代码内定义的常量,方括号内容为匿名化字符串):

credentials = gspread.service_account(filename=r'[JSON_FILE_PATH]')
spreadsheet = credentials.open_by_url('[GOOGLE_SHEET_URL]') 
worksheet = spreadsheet.worksheet(WORKSHEET_NAME) 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:51:00