【问题标题】:How do I export a Google sheet as a CSV in Python without using pandas?如何在不使用 pandas 的情况下在 Python 中将 Google 工作表导出为 CSV?
【发布时间】:2020-12-26 21:19:54
【问题描述】:

我正在使用 Python 3.9 和以下版本的 Google 表格 ...

gsheets==0.5.1
gspread==3.6.0

我正在尝试将我的 Google 工作表导出为 CSV 文件。在旧版本的 Python 中,我像这样使用 Pandas 模块

    import gspread
    ...
    client = gspread.authorize(creds)
    sheet = client.open('My_Sheet_name')

    # get the third sheet of the Spreadsheet.  This
    # contains the data we want
    sheet_instance = sheet.get_worksheet(3)

    records_data = sheet_instance.get_all_records()

    records_df = pd.DataFrame.from_dict(records_data)

    # view the top records
    records_df.to_csv(sys.stdout)  

如何在不使用 Pandas 的情况下导出 CSV?我问是因为似乎较新版本的 Python(例如 3.9)还不支持 pandas 模块。

【问题讨论】:

    标签: python-3.x csv google-sheets gspread


    【解决方案1】:

    我相信你的目标如下。

    • 您想检索 Google 电子表格中的一张工作表作为 CSV 数据。
    • 您想在不使用 Pandas 的情况下使用 gspread 实现此目的。
    • 您已经可以使用 gspread。

    在这种情况下,为了实现您的目标,我想建议使用端点将工作表导出为 CSV 数据。从clientclient = gspread.authorize(creds) 检索访问令牌。当这个提议反映到你的脚本中时,它变成如下。

    修改脚本:

    client = gspread.authorize(creds)
    sheet = client.open('My_Sheet_name')
    
    # get the third sheet of the Spreadsheet.  This
    # contains the data we want
    sheet_instance = sheet.get_worksheet(2)  # Modified
    
    # I added below script.
    url = 'https://docs.google.com/spreadsheets/d/' + sheet.id + '/gviz/tq?tqx=out:csv&gid=' + str(sheet_instance.id)
    headers = {'Authorization': 'Bearer ' + client.auth.token}
    res = requests.get(url, headers=headers)
    print(res.text)
    
    • 在上面的脚本中,请添加import requests
    • 运行上述脚本时,第三张工作表将导出为 CSV 数据。

    注意:

    • 关于sheet_instance = sheet.get_worksheet(3),你的评论说get the third sheet of the Spreadsheet.。但是get_worksheet 的第一个数字是0。因此,在这种情况下,将检索电子表格中的第四张工作表。请注意这一点。

    • 在这种情况下,我认为您也可以使用如下端点。

        url = 'https://docs.google.com/spreadsheets/d/' + sheet.id + '/export?format=csv&gid=' + str(sheet_instance.id)
      

    【讨论】:

      【解决方案2】:

      您可以使用 csv 模块中的 DictWriter 将每个字典作为单独的行添加到 csv 结果中:

      import sys
      from csv import DictWriter
      
      dict_writer = DictWriter(sys.stdout, records_data[0].keys())
      dict_writer.writeheader()
      for data in records_data:
          dict_writer.writerow(data)
      

      如果你想将 csv 写入文件而不是标准输出,你可以使用这个 sn-p 代替:

      from csv import DictWriter
      
      with open('./path/to/the/file', 'w') as csvfile:
          dict_writer = DictWriter(csvfile, records_data[0].keys())
          dict_writer.writeheader()
          for data in records_data:
              dict_writer.writerow(data)
      

      示例:

      records_data 包含以下值:[{'a': 1, 'b': 2}, {'a': 2, 'b': 3}, {'a': 3, 'b': 4}]

      然后标题取自列表中任意元素的键(在本例中为第一个):ab

      然后将值逐行添加到csv中:

      a, b
      1, 2
      2, 3
      3, 4
      

      【讨论】:

      • 你的意思是让我把“records_data = [dict(zip(records_data.keys(), i)) for i in zip(*records_data.values())]”放在“records_data = sheet_instance.get_all_records()”?我试过这个但得到错误,“AttributeError:'list'对象没有属性'values'”
      • @Dave get_all_records() 方法已经以正确的格式返回数据。所以你可以简单地跳过第一步。我会相应地更新我的答案。
      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2014-05-12
      • 2021-11-21
      相关资源
      最近更新 更多