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"])

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

在 Python3.4 中执行此操作的标准方法是什么?

4

1 回答 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
于 2016-01-30T09:54:19.680 回答