2016-10-13 43 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'是「更好」的原因是因爲它會在範圍結束時自動關閉文件,即使當中間出現異常。 –

相關問題