使用gspread在Colaboratory访问表格报错:service_account属性不存在
解决gspread中
module 'gspread' has no attribute 'service_account'的问题 问题根源:你当前安装的gspread版本低于5.0.0,
service_account()是gspread 5.0.0及以上版本才引入的新认证方法,旧版本不存在这个属性。快速修复步骤:
- 在Colaboratory中执行升级命令,将gspread更新到最新版本:
!pip install --upgrade gspread - (可选)验证版本是否达标:
确认输出的版本号≥5.0.0即可。import gspread print(gspread.__version__) - 重新运行你的代码,注意替换代码中的占位符:
- 将
[link_to_the_service_account_json_file]替换为你上传到Colab的服务账号JSON文件的实际文件名(比如my-service-account.json) - 将
[link_to_the_sheet]替换为已共享给该服务账号的谷歌表格链接 - 将
[sheetname]替换为目标工作表的名称
- 将
- 在Colaboratory中执行升级命令,将gspread更新到最新版本:
旧版本兼容方案(不推荐):
如果暂时不想升级版本,可以使用旧的认证方式,代码示例如下:import gspread as gs import pandas as pd from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('your-service-account.json', scope) gc = gs.authorize(creds) sh = gc.open_by_url('[link_to_the_sheet]') ws = sh.worksheet('[sheetname]') df = pd.DataFrame(ws.get_all_records()) df.head()注:该方案依赖
oauth2client库,如果未安装需执行!pip install oauth2client,但此认证方式已逐渐被官方弃用,建议优先升级gspread。
内容的提问来源于stack exchange,提问作者Samuel Mwamburi
相关产品推荐
相关产品推荐

