【问题标题】:Push the csv file data to google sheets将 csv 文件数据推送到谷歌表格
【发布时间】:2020-02-10 05:21:54
【问题描述】:

我需要将 csv 文件数据加载到谷歌表格。我使用 gspread 将 csv 导入到谷歌表格,但它只能用于个人驱动器而不是团队驱动器。

这是我的下一个方法。

我尝试将 csv 文件的内容放到列表中,然后从列表中更新 google 表格的单元格,结果出现 429 错误。我怎样才能避免这个错误?

row = 1
column = 1
Fi = []
Fi = open("data.csv",'r')
for value in Fi:
    items = value.strip().split(',')
    for item in items:
        sheet.update_cell(row, column, item)
        column +=1
    row +=1
    column = 1

sheet.update_cells(cell_list)
Fi.close()

这是我得到的错误

gspread.exceptions.APIError: {
  "error": {
    "code": 429,
    "message": "Quota exceeded for quota group 'WriteGroup' and limit 'Write requests per user per 100 seconds' of service 'sheets.googleapis.com' for consumer 'project_number:226307199654'.",
    "status": "RESOURCE_EXHAUSTED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developer console API key",
            "url": "https://console.developers.google.com/project/<proj_num>/apiui/credential"
          }
        ]
      }
    ]
  }
}

【问题讨论】:

  • 经常调用gsheet api会报错,或许可以加time sleep,降低api调用率

标签: python csv google-sheets python-requests gspread


【解决方案1】:

我认为如果您跟踪写入请求并且仅根据每 100 秒分配的配额发送请求,则可以解决此问题。并使用睡眠功能等待配额在 100 秒后重置。

import time

row = 1
column = 1
requestCount = 0
writeQuota = 100 #This is the limit for write request per 100 seconds
Fi = []
Fi = open("data.csv",'r')
for value in Fi:
    items = value.strip().split(',')
    for item in items:
        if(requestCount == writeQuota):
            time.sleep(100)
            requestCount = 0
        sheet.update_cell(row, column, item)
        requestCount += 1
        column += 1
    row += 1
    column = 1

sheet.update_cells(cell_list)
Fi.close()

尝试检查这样的方法是否有效。还可以调整睡眠时间并仔细检查您的写入配额。

【讨论】:

    【解决方案2】:

    每次请求完成时尝试使用睡眠功能。由于上述错误,您需要在每次写入请求完成后等待 100 秒以上。

    【讨论】:

      【解决方案3】:

      您经常致电update_cells。 根据gspread 文档here

      你可以批量做:

      cell_list = worksheet.range('A1:C7')
      for cell in cell_list:
          cell.value = 'O_o'
      # Update in batch
      worksheet.update_cells(cell_list)
      

      所以,看来您的解决方案是:

      Fi = []
      Fi = open("data.csv",'r')
      items=[]
      for value in Fi:
          for item in value.strip().split(','):
              items.append(item)
      
      cell_list = worksheet.range('A1:ENDRANGE') # according to csv
      for cell, item in cell_list, items:
          cell.value=item
      
      sheet.update_cells(cell_list)
      Fi.close()
      

      我没有测试它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-07
        • 2019-03-25
        • 2019-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多