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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
excelguy
  • 1,574
  • 6
  • 33
  • 67
  • of what type is your variable `values`? `b""` seems not appropriate here since `write` expects a `str`, not `byte` (as the error says) – FObersteiner Jul 29 '19 at 14:42

1 Answers1

5

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Seems to work, a mistake in my question : I had "values" in my code, not "headers" – excelguy Jul 29 '19 at 14:52
  • so you still can't write the `headers` variable? Or is it all working now? – FObersteiner Jul 29 '19 at 14:55
  • it working, thank you. – excelguy Jul 29 '19 at 14:58
  • This is not how you decode bytes values though. You concatenated `b'....'` strings, the `repr()` representations. Instead, use `bytes.decode()`. – Martijn Pieters Aug 07 '19 at 20:57
  • @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. – FObersteiner Aug 08 '19 at 06:34
  • They probably have little idea what they are doing, and are just trying the exception to go away. The question states they tried random things they found on Stack Overflow, at any rate. With a variable named `headers` this is probably HTTP so should be decoded as Latin-1, not UTF-8 (the default for `.decode()`. – Martijn Pieters Aug 10 '19 at 09:09