将二进制数据写入python3中的文件

时间:2013-11-21 19:34:46

标签: python-3.x bytearray binaryfiles

我一直遇到很多麻烦,而其他问题似乎并不是我想要的。所以基本上我有一个从

获得的字节列表
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

1 个答案:

答案 0 :(得分: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))

所以字节可以取一个字节值数组(即使它们在数组中以十进制形式表示)并通过强制转换将其转换为正确的byteArray

相关问题