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

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

In the final lines when outputting the 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 is an error like

TypeError: 'str' does not support the buffer interface

which occurs in a line open_file_object.writerow(["PassengerId","Survived"]).

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

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

+4
source share
1 answer

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
+6

Source: https://habr.com/ru/post/1626636/


All Articles