如何在python中从二进制文件读取int16数组



我正在尝试解析一个二进制文件。该文件包含几个数据包,每个数据包以时间戳开始,然后定义一个数组(行和列各为一个int32(数组本身。我刚开始尝试解析一个数据包,但在读取数组时遇到了问题:

tsSize = 8
rowSize = 4
columnSize=4
thresholdVectorSize=4
targetsCandidatesVectorSize=4
centerOfMassVectorSize=4
bytesReadUpToNow=0
with open("C:\outputs\out.bin", mode='rb') as file: # b is important -> binary
fileContent = file.read()   
TimeS = struct.unpack("Q", fileContent[bytesReadUpToNow:bytesReadUpToNow+tsSize])[0]
bytesReadUpToNow+=tsSize
dt =datetime.datetime.fromtimestamp(TimeS/1000.0)
rows, columns = struct.unpack("ii", fileContent[bytesReadUpToNow:bytesReadUpToNow+rowSize+columnSize])
bytesReadUpToNow=bytesReadUpToNow+rowSize+columnSize
data = struct.unpack("h" * (rows*columns), fileContent[bytesReadUpToNow:rows*columns*2+bytesReadUpToNow])[0]
print(sys.getsizeof(data))
print(type(data))

有没有一种方法可以在python中预定义数组的大小?

您可以使用"字节数组":

ba=bytearray(1000)      # zero-filled                                                 
In:  sys.getsizeof(ba)                                                       
Out: 1057
In:  ba[0:10]                                                                
Out: bytearray(b'x00x00x00x00x00x00x00x00x00x00')
In:  ba[5]=255                                                              
In:  ba[0:10]                                                               
Out: bytearray(b'x00x00x00x00x00xffx00x00x00x00')

编辑:

with open("data","wb") as ff: 
ff.write(int.to_bytes(100,1,"big")) 
ff.write(int.to_bytes(300,2,"big")) 
ff.write(int.to_bytes(5001,4,"big")) 
ba=bytearray(7)
ba
Out: bytearray(b'x00x00x00x00x00x00x00')
with open("data","rb") as ff: 
ba[0:7]= ff.read(7) 
ba                                          
Out: bytearray(b'dx01,x00x00x13x89')
int.from_bytes(ba[0:1],"big")
Out: 100
int.from_bytes(ba[1:3],"big")
Out: 300
int.from_bytes(ba[3:],"big") 
Out: 5001