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

ShanZhengYang picture ShanZhengYang · Jan 30, 2016 · Viewed 8.9k times · Source

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?

Answer

Tim Pietzcker picture Tim Pietzcker · Jan 30, 2016

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