2016-10-13 38 views
1

我的代码:如何解决TypeError:'str'不支持缓冲区接口?

big_int = 536870912 
f = open('sample.txt', 'wb') 

for item in range(0, 10): 
    y = bytearray.fromhex('{:0192x}'.format(big_int)) 
    f.write("%s" %y) 
f.close() 

我想一个长整型转换为字节。但我得到TypeError: 'str' does not support the buffer interface

+0

只是尝试'f.write(y)' –

+0

谢谢,它的工作原理 – rrra

回答

1

在Python 3中,字符串是隐式的Unicode,因此与特定的二进制表示(取决于所使用的编码)分离。因此,字符串"%s" % y不能写入以二进制模式打开的文件。

相反,你可以只写y直接把文件:

y = bytearray.fromhex('{:0192x}'.format(big_int)) 
f.write(y) 

而且,你其实代码("%s" % y)创建一个包含字符串表示的y Unicode字符串(即str(y))这不是你想象的那样。例如:

>>> '%s' % bytearray() 
"bytearray(b'')" 
3

除了@Will答案,最好是在使用with语句来打开你的文件。此外,如果您使用python 3.2及更高版本,则可以使用int.to_bytesint.from_bytes来反转该过程。

样品对我说的:

big_int=536870912 

with open('sample.txt', 'wb') as f: 
    y = big_int.to_bytes((big_int.bit_length() // 8) + 1, byteorder='big') 
    f.write(y) 
    print(int.from_bytes(y, byteorder='big')) 

最后print是向您展示如何扭转这种局面。

+3

只是为了增加:'with'是“更好”的原因是因为它会在范围结束时自动关闭文件,即使当中间出现异常。 –

相关问题