Skip to content

Instantly share code, notes, and snippets.

@geekman
Created December 7, 2011 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geekman/1441933 to your computer and use it in GitHub Desktop.
Save geekman/1441933 to your computer and use it in GitHub Desktop.
unpack struct from stream-like object
#
# example:
# f = open('/path/some/file', 'r')
# age, year, c = unpack('>HHB', f)
#
import struct
def unpack(fmt, f, offset=None):
"""Unpacks data read from file stream at optionally specified offset"""
isStruct = isinstance(fmt, struct.Struct)
size = fmt.size if isStruct else struct.calcsize(fmt)
pos = f.tell()
if offset is not None: f.seek(offset)
s = f.read(size)
if len(s) < size:
raise ValueError, "cannot unpack %s - not enough bytes read" % fmt
if offset is not None: f.seek(pos)
return fmt.unpack(s) if isStruct else struct.unpack(fmt, s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment