-2

I have a stable working project with python. It's running on python 2.7. I upgraded it to python 3.x. So, it's not working on Python3.

The logic is writing values to csv file.

Broken code is that:

csv = io.BytesIO()

csv.write('fiscalYear\t'
                      'VKN\t'
                      'recordPeriod\t'
                      'enteredBy\t'
                      'entredDate\t'
                      'entryNumber\t'
                      'entryComment\t'
                      'batchID\t'
                      'batchDescription\t'
                      'totalDebit\t'
                      'totalCredit\t'
                      'amountOriginalExchangeRate\t'
                      'amountOriginalExchangeRateSource\t'
                      'amountOriginalExchangeRateComment\n'
            )

return csv.getvalue()

My problem is that:

Expected type 'union[bytes, bytearray], got 'str' instead

Python log error:

TypeError: a bytes-like object is required, not 'str'

I need your help!

2 Answers2

2

As the error message says, you should pass binary data, not strings. Instead of

csv.write(my_text)

write

csv.write(my_text.encode())

to convert it to binary.

blue_note
  • 27,712
  • 9
  • 72
  • 90
2

You are writing a string (Unicode) to a BytesIO object. You should probably switch your BytesIO to a StringIO. If you truly want bytes, you can convert your Unicode strings to bytes using their encode() method, passing your preferred encoding scheme (e.g. 'utf-8').

John Zwinck
  • 239,568
  • 38
  • 324
  • 436