'str' 不支持 Python2 的缓冲区接口 Python3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26945613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:13:01  来源:igfitidea点击:

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

pythonstringpython-3.xunicodebytearray

提问by Daniel Domingo

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

嗨,这两个功能在 Py2 中工作正常,但在 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

回答by ekhumoro

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.

在 Python 2 中,裸文字字符串(例如'string')是bytes,而在 Python 3 中它们是unicode。这意味着如果您希望在 Python 3 中将文字字符串视为字节,则始终必须明确标记它们。

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

因此,例如,该encoding函数的前几行应如下所示:

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 Unicodefor more details.

有关更多详细信息,请参阅移植到 Python 3以及字节、字符串和 Unicode部分。

回答by Jimmy

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

在 python 3 中'w'是你需要的,而不是'wb'.