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

使用gspread在Colaboratory访问表格报错:service_account属性不存在

解决gspread中module 'gspread' has no attribute 'service_account'的问题
  • 问题根源:你当前安装的gspread版本低于5.0.0,service_account()是gspread 5.0.0及以上版本才引入的新认证方法,旧版本不存在这个属性。

  • 快速修复步骤:

    1. 在Colaboratory中执行升级命令,将gspread更新到最新版本:
      !pip install --upgrade gspread
      
    2. (可选)验证版本是否达标:
      import gspread
      print(gspread.__version__)
      
      确认输出的版本号≥5.0.0即可。
    3. 重新运行你的代码,注意替换代码中的占位符:
      • 将[link_to_the_service_account_json_file]替换为你上传到Colab的服务账号JSON文件的实际文件名(比如my-service-account.json)
      • 将[link_to_the_sheet]替换为已共享给该服务账号的谷歌表格链接
      • 将[sheetname]替换为目标工作表的名称
  • 旧版本兼容方案(不推荐):
    如果暂时不想升级版本,可以使用旧的认证方式,代码示例如下:

    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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:21:36