Python: Unpacking binary file into a 2-d array and giving a length error
<p>I'm trying to read in data from a file in binary format and store it in a 2-d array. However, I'm getting an error that reads</p>

<pre><code>error: unpack requires a bytes object of length 2
</code></pre>

<p>Essentially what I have is something like</p>

<pre><code>import os, struct
from itertools import chain

packets = value1  #The number of packets in the data stream
dataLength = value2 #bytes of data per packet

packHeader = [[0 for x in range(14)] for y in range(packets)]
data = [[0 for x in range(dataLength)] for y in range(packets)]

for i in range(packets):
    packHeader[i][0] = struct.unpack('&gt;H', file.read(2))
    packHeader[i][1] = struct.unpack('&gt;H', file.read(2))
    ....
    packHeader[i][13] = struct.unpack('&gt;i', file.read(4))
    packHeader[i]=list(chain(*packHeader[i])) #Deals with the tuple issue ((x,),(y,),...) -&gt; (x,y,...)
    for j in range(dataLength):
        data[i][j] = struct.unpack('&lt;h', file.read(2))
</code></pre>

<p>When it gets to this point it produces the error above. I'm not sure why. Both <code>dataLength</code> and <code>packets</code> are even numbers. So, imagined unpacking 2 bytes at a time shouldn't be an issue. Any thoughts?</p>

<p><strong>EDIT</strong> I did check to see what would happen if I read in the data one byte at a time. So </p>

<pre><code>data[i][j] = struct.unpack('&lt;b', file.read(1))
</code></pre>

<p>and that worked fine. It just is not liking to unpack anything else. </p>

<p><strong>EDIT 2</strong> I also just went ahead and made that slightly more compact by saying something like </p>

<pre><code>data[i] = [struct.unpack('&lt;h', file.read(2)) for j in range(dataLength)]
</code></pre>

<p>Still produces the same error - just more compactly.</p>