[Tutor] more on reading binary... a better way?

John washakie at gmail.com
Wed Sep 5 22:56:33 CEST 2007


Hello everyone,

Here's my solution for reading binary data (unformatted mixed types) and
packing it into a dictionary. It works, but somehow doesn't seem so
'pythonic'. Just seeking comments on how I might make it more efficient.
Thanks!

def readheader(filename):
 import struct
 I={0:'rl',1:'ibdate',2:'ibtime',3:'version',4:'void1',5:'void2',6:'loutstep',7:'loutaver',8:'loutsample',9:'void3',10:'void4',11:'outlon0',12:'oulat0',13:'numxgrid',14:'numygrid',15:'dxout',16:'dyout',17:'void5',18:'void6',19:'numzgrid'}
 B={}
 f2=file(filename,'rb')
 #Define Header format
 Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i']
#format for binary reading first bits
 if f2:
  print filename + ' has been opened'
  #create a dictionary from header file
  a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt]
  for i in range(len(a)):
   B[I[i]]=a[i][0]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070905/4bdfaca9/attachment.htm 


More information about the Tutor mailing list