'str' 不支持 Python2 的缓冲区接口 Python3 [英] 'str' does not support the buffer interface Python3 from Python2

查看:24
本文介绍了'str' 不支持 Python2 的缓冲区接口 Python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个功能在 Py2 中工作正常,但在 Py3 上不起作用

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

控制台输出:

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

In python 3 'w' is what you need, not 'wb'.

这篇关于'str' 不支持 Python2 的缓冲区接口 Python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆