我正在尝试将私人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很新,我正试图解决这个问题。任何人都可以指出我使用的代码有什么问题吗?
答案 0 :(得分:3)
在Python 3中,以文本模式打开文件,并将newline
设置为''
,让CSV编写器控制写入的换行符:
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(worksheet.get_all_values())
答案 1 :(得分:0)
(2016年7月)现在访问Google表格文件时,GData的使用已过时。目前将Google Sheet导出为CSV的现代方法是使用Google Drive API。我用Python 2 + 3代码示例编写了一个blogpost,向您展示了如何执行此操作。另外检查我添加了比2012更现代的答案的其他线程。通过该更新,该线程应标记为另一个的副本。要从更一般的意义上从Python访问Google表格,请查看this answer I gave相关问题。