Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: write() argument must be str, not byte , upgrade to python 3 [duplicate]

I am trying to upgrade my code to python 3. Having some trouble with this line,

output_file = open(working_dir + "E"+str(s)+".txt", "w+")

output_file.write(','.join(headers) + "\n")

and get this error TypeError: sequence item 0: expected str instance, bytes found

What i've tried,

  output_file.write(b",".join(headers) + b"\n")

TypeError: write() argument must be str, not bytes

ive also tried using decode() on the join, also tried using r and w+b on open.

How can i convert to str in python 3?

like image 572
excelguy Avatar asked Jul 26 '19 19:07

excelguy


1 Answers

EDIT: to read on how to convert bytes to string, follow the link provided by Martijn Pieters in the 'duplicate' tag.

my original suggestion

output_file.write(','.join([str(v) for v in values]) + "\n")

would give for example

values = [b'a', b'b', b'c']
print(','.join([str(v) for v in values]))
# b'a',b'b',b'c'

So despite this works, it might not be desired. If the bytes should be decoded instead, use bytes.decode() (ideally also with the appropriate encoding provided, for example bytes.decode('latin-1'))

values = [b'a', b'b', b'c']
print(','.join([v.decode() for v in values]))
# a,b,c
like image 194
FObersteiner Avatar answered Nov 13 '22 10:11

FObersteiner