[Pythonmac-SIG] reading/writing binary data?

Just van Rossum just@letterror.com
Thu, 21 Jan 1999 01:38:21 +0100


At 4:26 PM -0800 1/20/99, Joseph J. Strout wrote:
>>(Or even NumPy, but that might be overkill.)
>
>Actually, I *am* stuffing NumPy arrays from a file at one point.  But I
>didn't see any way to load such a beast from a file, other than reading it
>in parts as a string, converting to ints (now with struct.unpack), and
>stuffing it.  I suppose you're going to tell me I'm *still* doing it the
>hard way?

It's pretty easy with NumPy:

>>> from Numeric import *
>>> a = arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.tostring()
'\000\000\000\000\000\000\000\001\000\000\000\002\000\000\000\003\000\000\000\00
4\000\000\000\005\000\000\000\006\000\000\000\007\000\000\000\010\000\000\000\01
1'
>>> fromstring(_, Int)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>

If you don't need to be compatible with other apps and if you use a recent
NumPy you can also use cPickle: it's really fast and convenient.

Just