【问题标题】:Finding the file_id of a spreadsheet using gspread使用 gspread 查找电子表格的 file_id
【发布时间】:2019-06-02 17:23:21
【问题描述】:

我正在尝试清理我的 Google 服务帐户中的一些空间。我一直在用它来处理电子表格,我想删除一些我之前创建的电子表格。要删除电子表格,请在 gspread 中使用 gc.del_spreadsheet(file_id) 函数。但是,我找不到一种方法来检索要删除的电子表格的文件 ID。

我找不到像打开个人帐户的谷歌驱动器一样打开服务帐户的谷歌驱动器的方法。因此,我使用以下代码列出了截至目前帐户中的所有电子表格。该代码输出电子表格标题,但不输出删除电子表格所需的文件 ID。

def upload_to_google_sheets():
    scope = ['https://spreadsheets.google.com/feeds',
             'https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name("client.json", scope)
    gc = gspread.authorize(credentials)
    print('authorized')
    titles_list = []
    for spreadsheet in gc.openall():
        titles_list.append(spreadsheet.title)

    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(titles_list)

upload_to_google_sheets()

最终目标是使用需要“file_id”的 gspread del_spreadsheet 函数删除电子表格。

【问题讨论】:

    标签: python drive gspread


    【解决方案1】:
    • 您想使用 gspread 检索电子表格标题和电子表格 ID。

    如果我的理解是正确的,那么这个修改呢?

    发件人:

    titles_list.append(spreadsheet.title)
    

    收件人:

    titles_list.append({'title': spreadsheet.title, 'id': spreadsheet.id})
    
    • for spreadsheet in gc.openall(): 的对象 spreadsheet 包含电子表格 ID。
    • 要检索电子表格 ID,请在您的脚本中使用 spreadsheet.id

    通过这个修改,可以得到如下结果。

    [   {   'id': '### Spreadsheet ID1 ###',
            'title': '### Spreadsheet name1 ###'},
        {   'id': '### Spreadsheet ID2 ###',
            'title': '### Spreadsheet name2 ###'},
    ,
    ,
    ,
    ]
    

    参考:

    如果我误解了您的问题并且这不是您想要的结果,我深表歉意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 2023-03-19
      • 1970-01-01
      • 2016-01-26
      相关资源
      最近更新 更多