【问题标题】:Python 3 - Saving a google spreadsheet as a csvPython 3 - 将谷歌电子表格保存为 csv
【发布时间】:2014-04-13 11:15:01
【问题描述】:

我正在尝试将私人 google 电子表格保存到 csv 中。我找到了另一个解决了这个问题的线程(Download a spreadsheet from Google Docs using Python),但是答案可以追溯到 2012 年。我尝试使用一个解决方案,但我遇到了错误。这是我目前使用的代码

import csv
import gspread

// used the actual username, password and doc-id in the python script
username = "username"
password = "password"
docid = "doc-id"

client = gspread.login(username, password)
spreadsheet = client.open_by_key(docid)

for i, worksheet in enumerate(spreadsheet.worksheets()):
    filename = docid + '-worksheet' + str(i) + '.csv'
    with open(filename, 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(worksheet.get_all_values())

这是 IDLE 抛出的错误

writer.writerows(worksheet.get_all_values())
TypeError: 'str' does not support the buffer interface

您一定已经意识到,我对 python 非常陌生,我正在努力解决这个问题。谁能指出我使用的代码有什么问题?

【问题讨论】:

    标签: python csv python-3.x google-docs


    【解决方案1】:

    在 Python 3 中,以文本模式打开文件,并将 newline 设置为 '' 以让 CSV 编写器控制写入哪些换行符:

    with open(filename, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(worksheet.get_all_values())
    

    【讨论】:

    • 这就像一个魅力。答案速度惊人。万分感谢。 :D.
    【解决方案2】:

    (2016 年 7 月) 现在访问 Google 表格文件时使用 GData 已过时。当前将 Google 表格导出为 CSV 的现代方法是使用 Google Drive API。我用 Python 2+3 代码示例写了一个blogpost,向您展示了如何执行此操作。还要检查我添加的答案比 2012 年更现代的另一个线程。通过该更新,该线程应标记为另一个线程的副本。要在更一般的意义上从 Python 访问 Google 表格,请查看this answer I gave 到相关问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      相关资源
      最近更新 更多