【发布时间】: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 3.4,您需要转换为
bytes或以“wt”模式打开 -
@PadraicCunningham
'w'就够了。 -
docs.python.org/3/tutorial/… - 注意从 2.x 开始的变化。
标签: python string python-3.x unicode bytearray