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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With