reading in ints from binary files

Brian Quinlan brian at sweetapp.com
Mon Mar 25 15:29:37 EST 2002


Bill wrote:
> However, is there an easier way of doing this?  I currently do
something
> like:
> 
> f=open('file', 'rb')
> s = f.readline()
> l = list(s[0:-1])
> l.reverse()
> a = array.array('h', ''.join(l))
> 
> There's gotta be an easier way.

I'm not really sure what problem you are trying to solve but this might
help:

f = open('file', 'rb')
my_list = array('h', f.read()).tolist()
# my_list is now a list of Python integers, which you can manipulate as
# usual

The use of readline seems crazy to me; it will cause problems if your
integers happen to contain the byte 0x0a.

Cheers,
Brian





More information about the Python-list mailing list