title: reading a binary file in python
body: <p>I have to read a binary file in python. This is first written by a Fortran 90 program in this way:</p>
  
  <pre><code>open(unit=10,file=filename,form='unformatted')
  write(10)table%n1,table%n2
  write(10)table%nH
  write(10)table%T2
  write(10)table%cool
  write(10)table%heat
  write(10)table%cool_com
  write(10)table%heat_com
  write(10)table%metal
  write(10)table%cool_prime
  write(10)table%heat_prime
  write(10)table%cool_com_prime
  write(10)table%heat_com_prime
  write(10)table%metal_prime
  write(10)table%mu
  if (if_species_abundances) write(10)table%n_spec
  close(10)
  </code></pre>
  
  <p>I can easily read this binary file with the following IDL code:</p>
  
  <pre><code>n1=161L
  n2=101L
  openr,1,file,/f77_unformatted
  readu,1,n1,n2
  print,n1,n2
  spec=dblarr(n1,n2,6)
  metal=dblarr(n1,n2)
  cool=dblarr(n1,n2)
  heat=dblarr(n1,n2)
  metal_prime=dblarr(n1,n2)
  cool_prime=dblarr(n1,n2)
  heat_prime=dblarr(n1,n2)
  mu  =dblarr(n1,n2)
  n   =dblarr(n1)
  T   =dblarr(n2)
  Teq =dblarr(n1)
  readu,1,n
  readu,1,T
  readu,1,Teq
  readu,1,cool
  readu,1,heat
  readu,1,metal
  readu,1,cool_prime
  readu,1,heat_prime
  readu,1,metal_prime
  readu,1,mu
  readu,1,spec
  print,spec
  close,1
  </code></pre>
  
  <p>What I want to do is reading this binary file with Python. But there are some problems.
  First of all, here is my attempt to read the file:</p>
  
  <pre><code>import numpy
  from numpy import *
  import struct
  
  file='name_of_my_file'
  with open(file,mode='rb') as lines:
      c=lines.read()
  </code></pre>
  
  <p>I try to read the first two variables:</p>
  
  <pre><code>dummy, n1, n2, dummy = struct.unpack('iiii',c[:16])
  </code></pre>
  
  <p>But as you can see I had to add to dummy variables because, somehow, the fortran programs add the integer 8 in those positions. </p>
  
  <p>The problem is now when trying to read the other bytes. I don't get the same result of the IDL program.</p>
  
  <p>Here is my attempt to read the array n</p>
  
  <pre><code> double = 8
   end = 16+n1*double
   nH = struct.unpack('d'*n1,c[16:end])
  </code></pre>
  
  <p>However, when I print this array I get non sense value. I mean, I can read the file with the above IDL code, so I know what to expect. So my question is: how can I read this file when I don't know exactly the structure? Why with IDL it is so simple to read it? I need to read this data set with Python.</p>