"str" 不支持 Python3 中的缓冲区接口,这是从 Python2 迁移时需要注意的问题。

13

嗨,我有这两个在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

2
如果使用Python 3.4,则需要将其转换为“bytes”或以“wt”模式打开。 - Padraic Cunningham
'w'就足够了。 - simonzack
请注意2.x版本的更改:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files - Karl Knechtel
可能是重复的问题:TypeError: 'str' does not support the buffer interface - kenorb
2个回答

21

修复对我来说很简单

使用

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

取代

f = open('bytes.bin', 'wb') 
在Python 3中,你需要使用'w'而不是'wb'

13
在Python 2中,裸字符串(例如'string')是字节,而在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)

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

详见迁移到Python 3字节、字符串和Unicode部分获取更多细节。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接