'str' does not support the buffer interface Python3 from Python2

后端 未结 2 1406
鱼传尺愫
鱼传尺愫 2020-12-10 04:29

Hi have this two funtions in Py2 works fine but it doesn´t works on Py3

def encoding(text, codes):
    binary = \'\'
    f = open(\'bytes.bin\', \'wb\')
             


        
相关标签:
2条回答
  • 2020-12-10 04:48

    The fix was simple for me

    Use

    f = open('bytes.bin', 'w')
    

    instead of

    f = open('bytes.bin', 'wb') 
    

    In python 3 'w' is what you need, not 'wb'.

    0 讨论(0)
  • 2020-12-10 04:53

    In Python 2, bare literal strings (e.g. 'string') are bytes, whereas in Python 3 they are unicode. This means if you want literal strings to be treated as bytes in Python 3, you always have to explicitly mark them as such.

    So, for instance, the first few lines of the encoding function should look like this:

    binary = b''
    f = open('bytes.bin', 'wb')
    for c in text:
        binary += codes[c]
    f.write(b'%s' % binary)
    

    and there are a few lines in the other function which need similar treatment.

    See Porting to Python 3, and the section Bytes, Strings and Unicode for more details.

    0 讨论(0)
提交回复
热议问题