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
相关产品推荐
相关产品推荐

