reading in ints from binary files
Chris Liechti
cliechti at gmx.net
Mon Mar 25 15:25:05 EST 2002
"Bill" <metaliu at yahoo.com> wrote in news:a7ns1d$mi1$1
@nntp1.jpl.nasa.gov:
> Quick Newb question:
>
> How do I read in integers from binary files? readlines() reads
returns
> the data in as a string. I can manipulate the string to get the
> desired result. 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 usualy use the struct module.
a = struct.unpack("<HHHHH", f.read(10))
don't use "readline" on binary files as it will only read to a 0x1a
wich can occour randomly in binary data. with "read(size)" with size
appropriate for your fileformat (e.g. one record at a time)
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list