Python 3 - 将Google表格另存为CSV

2 投票
2 回答
3889 浏览
提问于 2025-04-17 21:37

我想把一个私人谷歌表格保存成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 个回答

0

(2016年7月) 现在使用GData来访问Google Sheets文件已经过时了。现在更现代的方法是通过Google Drive API将Google表格导出为CSV格式。我写了一篇博客文章,里面有Python 2和3的代码示例,教你怎么做。此外,还可以查看我在另一个讨论串中添加的答案,那是比2012年更新的内容。根据这个更新,这个讨论串应该标记为与另一个讨论串重复。如果你想更一般地了解如何从Python访问Google Sheets,可以看看我对相关问题的这个回答

3

在Python 3中,打开文件时选择文本模式,并把 newline 设置为 '',这样CSV写入器就可以控制写入的换行符。

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

撰写回答