13

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?

1
  • of what type is your variable values? b"" seems not appropriate here since write expects a str, not byte (as the error says) Commented Jul 29, 2019 at 14:42

1 Answer 1

5
+50

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
Sign up to request clarification or add additional context in comments.

6 Comments

Seems to work, a mistake in my question : I had "values" in my code, not "headers"
so you still can't write the headers variable? Or is it all working now?
it working, thank you.
This is not how you decode bytes values though. You concatenated b'....' strings, the repr() representations. Instead, use bytes.decode().
@MartijnPieters, thanks for the comment. I made an edit to clarify on that - although the question does not ask explicitly for decoding, it is most likely the desired procedure.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.