尝试创建CSV文件,继续获取TypeError:' str'不支持缓冲区接口

时间:2016-05-23 15:55:28

标签: python python-3.x

我正在尝试创建CSV文件。我将代码键入pythons IDLE python版本3.4.3并获得以下内容 (我不明白为什么我会得到TypeError:' str',我的系数中没有str类型)

with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow([3,4])
    spamwriter.writerow([6,7])



Traceback (most recent call last):
  File "<pyshell#54>", line 4, in <module>
    spamwriter.writerow([3,4])
TypeError: 'str' does not support the buffer interface

1 个答案:

答案 0 :(得分:2)

您需要使用wt作为文件模式,而不是wb。当csv模块期望以文本模式打开文件时,wb以二进制模式打开文件。

此外,如果您使用的是Windows,则需要使用open('eggs.csv', 'wt', newline='')打开该文件,否则您最终会在每行之间添加一个空白行。< / p>