gpt4 book ai didi

python - 'str' 不支持来自 Python2 的缓冲区接口(interface) Python3

转载 作者:太空狗 更新时间:2023-10-29 17:23:16 25 4
gpt4 key购买 nike

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

最佳答案

修复对我来说很简单

使用

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

代替

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

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

关于python - 'str' 不支持来自 Python2 的缓冲区接口(interface) Python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26945613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com