[python-win32] How to parse a binary file
David Ransier
David.Ransier@digital2me.com
Thu, 5 Jul 2001 14:12:27 -0700
I've never written a binary parser before, so I'm looking for some starting
point.
I want to read an image file (Sun Raster format: RAS) and parse the included
color map, writing the color map as a text file (possible CSV format).
I can open the file in "rb" mode and read a certain number of bytes. But
when I try to do something with the value, Python complains that it's not in
the correct format.
Here is some sample code for reading the file (Magic is a 4-byte ID that
identifies the file as RAS format.)
import sys
infile = "TestImage.ras"
try:
FH = open(infile, 'rb')
except IOError, eStr:
print "ERROR: Cannot open ", infile, " for reading: ", eStr
sys.exit()
Magic = FH.read(4)
print "Magic: %d" % (Magic)
I tried coercing Magic to an int, but that didn't help.
Thanks,
David R
____________________________________________
David Ransier
David.Ransier@digital2me.com
Office: 503-416-3812 111 SW 5th Ave.
Fax: 503-416-3801 Suite 2200
Mobile: 360-921-5584 Portland, OR 97204