By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,818 Members | 1,262 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,818 IT Pros & Developers. It's quick & easy.

Can not get struct to read the entire binary file.

P: n/a
I succeed in extracting all of the header information, and then only a portion of the data. The data section is 123,410 doubles, but after retrieving 62 of the numbers, I can not go further, struct.unpack indicates that the string argument is the wrong length. I set up a loop to get the numbers one at a time, and it stops at the same place. The file is not corrupt, and will open in the original software. Does anyone have suggestions for figuring out the problem?
Expand|Select|Wrap|Line Numbers
  1. import struct, string, os
  2.  
  3. bf = "F:/Junker/TestT/TU_TSA.grd"
  4. wbf = open(bf).read()  # "rb")
  5. start, stop = 0, struct.calcsize('<7l8d2l')
  6.  
  7. #Retrieve the header information
  8. try:
  9.     TheadID,TheadSize,HSver,TgridID,TgridSize,nRow,nCol,xLL,yLL,xSize,ySize,zMin,zMax,\
  10.     Rotation,BlankVal,TdataID,TdataSize = struct.unpack('<7l8d2l', wbf[start:stop])
  11. except:
  12.     print "Problem reading Header"
  13. print "TheadID ", TheadID, "\n ", "TheadSize ",TheadSize,"\n ","HSver ", HSver,"\n ","TheadID ",TgridID,"\n ","TgridSize ",TgridSize,"\n ","nRow ",nRow,"\n ","nCol ",nCol,"\n ","xLL ",xLL,"\n ","yLL ",yLL,"\n ","xSize ",xSize,"\n ","ySize ",ySize,"\n ","zMin ",zMin,"\n ","zMax ",zMax,"\n ","Rotation ",Rotation,"\n ","BlankVal ",BlankVal,"\n ","TdataID ",TdataID,"\n ","TdataSize",TdataSize
  14.  
  15. #Retrieve the data
  16. try:
  17.     x = nCol * nRow
  18.     while x:
  19.         start, stop = stop, stop + struct.calcsize('<d')
  20.         DataBlock = struct.unpack('<d', wbf[start:stop])
  21.         print DataBlock, " start ",start, " stop ",stop
  22.  
  23. except:
  24.     print "Failed at: start ",start, " stop ",stop
  25.  
  26. del TheadID,TheadSize,HSver,TgridID,TgridSize,nRow,nCol,xLL,yLL,xSize,ySize,zMin,zMax,\
  27.     Rotation,BlankVal,TdataID,TdataSize,start,stop
  28.  
Nov 3 '10 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 624
Test the length of "wbf" and see if it is approximately the same size as the file. Also it is not being read in binary mode:
Expand|Select|Wrap|Line Numbers
  1. ##  should be
  2. wbf = open(bf, "rb").read()  # "rb") 
Nov 3 '10 #2

P: 1
That is just embarrassing, I changed this so many times and tried so many things, that at some point I commented out the read binary mode, and never put it back. Grrrrrr.
Thank you for pointing out what I was too close to see.
Nov 4 '10 #3

Expert 100+
P: 624
The answer is usually embarrassingly simple _after_ you know it.
Nov 4 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.