【问题标题】:'str' does not support the buffer interface Python3 from Python2'str' 不支持 Python2 中的缓冲区接口 Python3
【发布时间】:2015-01-12 18:23:54
【问题描述】:

你好,这两个函数在 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

控制台输出如下:

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

【问题讨论】:

标签: python string python-3.x unicode bytearray


【解决方案1】:

修复对我来说很简单

使用

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

而不是

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

在 python 3 中,'w' 是您所需要的,而不是 'wb'

【讨论】:

    【解决方案2】:

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

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

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

    另外函数中有几行需要类似处理。

    有关详细信息,请参阅Porting to Python 3Bytes, Strings and Unicode 部分。

    【讨论】:

      猜你喜欢
      • 2016-05-08
      • 1970-01-01
      • 2011-07-25
      • 2015-08-08
      • 2014-08-09
      • 2023-03-10
      相关资源
      最近更新 更多