Python 3 - 将Google表格另存为CSV
我想把一个私人谷歌表格保存成CSV格式。我找到了一些相关的讨论(用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还不太熟悉,现在正在努力解决这个问题。有没有人能指出我用的代码有什么问题?
2 个回答
3
在Python 3中,打开文件时选择文本模式,并把 newline
设置为 ''
,这样CSV写入器就可以控制写入的换行符。
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(worksheet.get_all_values())