Python 3.1.3 Win 7: csv writow Error "must be bytes or buffer, not str"

Got a simple script that worked perfectly under Python 2.7.1 on my Win xp machine. Now got a car with a win of 7 with python 3.1.3.

Code:

owriter.writerow(dtime[1][1]) dtime[1][1]=['30-Aug-10 16:00:00', '2.5', '15'] 

This error message is TypeError: must be bytes or buffer, not str : TypeError: must be bytes or buffer, not str

What changes should I make?

thanks.

+4
source share
3 answers

You may need to open the file in text mode. If not, include enough of your code for it to work and demonstrate the problem.

+6
source

In Python 2.X, it was required to open csvfile with 'b' because the csv module does its string completion processing.

In Python 3.X, the csv module still does its own string termination processing, but still needs to know the encoding for Unicode strings. The correct way to open a csv file for writing is:

 outputfile=open("out.csv",'w',encoding='utf8',newline='') 

encoding can be anything you need, but newline='' suppresses newline='' processing in text mode. On Windows, this will not write the line endings of the file \ r \ r \ n instead of the correct \ r \ n. This is only mentioned in the 3.X documentation of csv.reader , but csv.writer also requires it.

+16
source

Change to str.encode("ascii") .

The fact is that Python 2.x had a somewhat mixed use of type str for storing byte buffers and for storing character strings. Now in Python 3.x we have proper Unicode support, and byte buffers are now a separate type. You can convert between them using str.encode() and bytes.decode() , defining each time the character encoding as a parameter.

0
source

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


All Articles