title: Reading an entire binary file into Python
body: <p>I need to import a binary file from Python -- the contents are signed 16-bit integers, big endian.</p>
  
  <p>The following Stack Overflow questions suggest how to pull in several bytes at a time, but is this the way to scale up to read in a whole file?</p>
  
  <ul>
  <li><p><em><a href="https://stackoverflow.com/questions/1035340/reading-binary-file-in-python">Reading some binary file in Python</a></em></p></li>
  <li><p><em><a href="https://stackoverflow.com/questions/875046/recieving-16-bit-integers-in-python">Receiving 16-bit integers in Python</a></em></p></li>
  </ul>
  
  <p>I thought to create a function like:</p>
  
  <pre><code>from numpy import *
  import os
  
  def readmyfile(filename, bytes=2, endian='&gt;h'):
      totalBytes = os.path.getsize(filename)
      values = empty(totalBytes/bytes)
      with open(filename, 'rb') as f:
          for i in range(len(values)):
              values[i] = struct.unpack(endian, f.read(bytes))[0]
      return values
  
  filecontents = readmyfile('filename')
  </code></pre>
  
  <p>But this is quite slow (the file is 165924350 bytes). Is there a better way?</p>