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

时间秒杀一切 提交于 2019-12-17 19:14:13

问题


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')
    for c in text:
        binary += codes[c]
    f.write('%s' % binary)
    print('Text in binary:', binary)
    f.close()
    return len(binary)

def decoding(codes, large):
    f = file('bytes.bin', 'rb')
    bits = f.read(large)
    tmp = ''
    decode_text = ''
    for bit in bits:
        tmp += bit
        if tmp in fordecodes:
            decode_text += fordecodes[tmp]
            tmp = ''
    f.close()
    return decode_text

The console ouputs this:

Traceback (most recent call last):
  File "Practica2.py", line 83, in <module>
    large = encoding(text, codes)
  File "Practica2.py", line 56, in encoding
    f.write('%s' % binary)
TypeError: 'str' does not support the buffer interface

回答1:


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'.




回答2:


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.



来源:https://stackoverflow.com/questions/26945613/str-does-not-support-the-buffer-interface-python3-from-python2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!