[Python-il] problem in script

Arik Baratz list+python at arik.baratz.org
Sun Dec 27 17:26:51 IST 2009

2009/12/28 Yitzhak Wiener <Yitzhak.Wiener at dspg.com>

Hi Yitzhak,
First let's make sure I understand what you want
> from array import array
> a = array('H')
> f =  file('project_release.a')
> a.fromfile( f,100 )

So far you've opened the input file, and provided it is more than 200
bytes, you've interpreted the first 200 bytes as 100 unsigned
double-bytes in machine order and put them into the array a. Note that
by default files are opened for reading. It is better to specify
explicitly that you want to open a binary file for reading using:

f =  file('project_release.a','rb')

> # update the content
> for i in a:
>    if i == 0xFFFF:
>        a[ a.index(i) ] = 0x7777

You've searched for the value 0xffff and replaced it with 0x7777. For
some reason you're doing the lookup twice - once by iterating over a,
and once by using the index() method. A better approach would be:

for i,val in enumerate(a):
   if val==0xffff:

the enumerate() builtin function returns values from the iterable (in
this case the array a is iterable) in a touple with their sequence.

> #update to new file
> a.tofile(f)

Here you might want to open a new file - f is opened read-only by default.
So my suggestion for your code would be:

import array

a = array.array('H') # unsigned short array

# read the first 100 values from the input file
f =  file('project_release.a','rb')
a.fromfile( f,100 )

# search and replace
for idx,val in enumerate(a):
   if val==0xffff:

# write into the output file
f = file('project_release-out.a','wb')

This program will return an exception (EOFError) if the input file is
smaller than 200 bytes. Also note that the values in the file will be
interpteted in machine order (i.e. big endian or little endian,
depending on the CPU). The output file size will be exactly 200 bytes.

-- Arik

More information about the Python-il mailing list