我将以下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中,标准的方法是什么?
newline=""'
引起的,这就是为什么我想要澄清。对于给您带来的困扰,我感到抱歉。 - 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