Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

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

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...