gpt4 book ai didi

Python3 CSV writerows,TypeError : 'str' does not support the buffer interface

转载 作者:太空狗 更新时间:2023-10-29 20:16:43 26 4
gpt4 key购买 nike

我正在将以下 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 中不起作用。但是,在 open() 中添加 encoding='utf8' 行也不起作用。

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

最佳答案

创建 CSV 文件在 Python 2 和 Python 3 之间是不同的(查看 csv module 的文档会显示):

代替

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

关于Python3 CSV writerows,TypeError : 'str' does not support the buffer interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com