Python3 CSV writerows,TypeError:'str'不支持缓冲区接口

9

我将以下Kaggle代码翻译成Python3.4:

在最后几行输出CSV文件时,

predictions_file = open("myfirstforest.csv", "wb")
open_file_object = csv.writer(predictions_file)
open_file_object.writerow(["PassengerId","Survived"])
open_file_object.writerows(zip(ids, output))
predictions_file.close()
print('Done.')

出现了类型错误

TypeError: 'str' does not support the buffer interface

这个问题发生在代码的这一行:open_file_object.writerow(["PassengerId","Survived"])

我认为这是因为在Python 3中,以二进制模式打开文件写入csv数据不起作用。然而,在open()行中添加encoding='utf8'也无效。

在Python 3.4中,标准的方法是什么?

1个回答

13

Python 2和Python 3中创建CSV文件的方式有所不同(查看csv模块文档即可了解):

与其使用

predictions_file = open("myfirstforest.csv", "wb")

你需要使用

predictions_file = open("myfirstforest.csv", "w", newline="")

(如果发生错误,您应该使用上下文管理器来处理文件的关闭):

with open("myfirstforest.csv", "w", newline="") as predictions_file:
    # do stuff
# No need to close the file

正如查看csv模块文档所示,我意识到这一点(并在原始问题中提到了它,用英语表述)。我没有理解错误是由newline=""'引起的,这就是为什么我想要澄清。对于给您带来的困扰,我感到抱歉。 - ShanZhengYang
1
@ShanZhengYang 为了清晰起见:'wb'以二进制模式打开文件,因此.write()期望二进制数据,例如bytes对象,而不是Python 3中的Unicode字符串。'w'以文本模式打开文件:.write()期望str。Python 3.5生成更易懂的错误消息:TypeError: a bytes-like object is required, not 'str'newline =""与此问题无关,但建议在csv文件中使用(csv模块即使在Unix上也使用b'\r\n'newline=''允许写入换行符而不进行通用换行符模式转换('\n'-> os.linesep))。 - jfs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接