Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am translating the following Kaggle code into Python3.4:

In the final lines when outputting a CSV file,

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.')

there's a Type Error

TypeError: 'str' does not support the buffer interface

which occurs at the line open_file_object.writerow(["PassengerId","Survived"]).

I believe this is because Opening a file in binary mode to write csv data to doesn't work in Python 3. However, adding encoding='utf8' in the open() line doesn't work either.

What is the standard way to do this in Python3.4?

like image 293
ShanZhengYang Avatar asked Jan 30 '16 09:01

ShanZhengYang


1 Answers

Creating a CSV file is different between Python 2 and Python 3 (as a look into the docs for the csv module would have shown):

Instead of

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

you need to use

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

(And you should use a context manager to handle the closing of the file for you, in case an error does occur):

with open("myfirstforest.csv", "w", newline="") as predictions_file:
    # do stuff
# No need to close the file
like image 190
Tim Pietzcker Avatar answered Oct 12 '22 21:10

Tim Pietzcker