2013-11-21 62 views
1

我一直有這個問題很多,其他問題似乎並不是我正在尋找的。所以基本上我有將二進制數據寫入python3中的文件

bytes = struct.pack('I',4) 
bList = list(bytes) 
# bList ends up being [0,0,0,4] 
# Perform some operation that switches position of bytes in list, etc 

得到字節的列表所以現在我想寫這一個文件

f = open('/path/to/file','wb') 
for i in range(0,len(bList)): 
    f.write(bList[i]) 

但我不斷收到錯誤

TypeError: 'int' does not support the buffer interface 

我已經也試過寫:

bytes(bList[i]) # Seems to write the incorrect number. 
str(bList[i]).encode() # Seems to just write the string value instead of byte 

回答

2

哦小子,我不得不通過籃球來解決這個問題。所以基本上我不得不代替做

bList = bytes() 
bList += struct.pack('I',4) 

# Perform whatever byte operations I need to 

byteList = [] 

# I know, there's probably a list comprehension to do this more elegantly 
for i in range(0,len(bList)): 
    byteList.append(bList[i]) 

f.write(bytes(byteList)) 

所以字節可以字節值(即使它們在數組中的十進制形式正在爲代表)的陣列,它由鑄造

轉換爲字節組合適