Sha*_*ang 9 python csv typeerror python-3.x kaggle
我正在将以下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.')
Run Code Online (Sandbox Code Playgroud)
有一个类型错误
TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)
发生在线上open_file_object.writerow(["PassengerId","Survived"]).
我相信这是因为在二进制模式打开文件写入CSV数据不会出现在Python 3的工作.然而,增加encoding='utf8'的open()行也不行.
在Python3.4中执行此操作的标准方法是什么?
Tim*_*ker 12
在Python 2和Python 3之间创建CSV文件是不同的(查看csv模块的文档将会显示):
代替
predictions_file = open("myfirstforest.csv", "wb")
Run Code Online (Sandbox Code Playgroud)
你需要使用
predictions_file = open("myfirstforest.csv", "w", newline="")
Run Code Online (Sandbox Code Playgroud)
(并且您应该使用上下文管理器为您处理文件的关闭,以防发生错误):
with open("myfirstforest.csv", "w", newline="") as predictions_file:
# do stuff
# No need to close the file
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8435 次 |
| 最近记录: |