[Python-il] problem in script

Beni Cherniavsky cben at users.sf.net
Sun Dec 27 16:31:51 IST 2009


[Imri beat me to it, but replying anyway in case a more detailed answer
helps.]

First question: are you on Windows or Linux/Mac?
On windows, you must open the file as binary, or CR LF will be read as LF,
killing the binary meaning:
f =  file('project_release.a', *'rb'*)
On Linux/Mac, it doesn't matter, but it's good practice to do it anyway for
portability.

Second problem: you use the same file handle for reading and writing.
Normal file object are open either for reading, or writing.  Your is open
for reading (the default).

[If this is indeed the problem, tofile() should have given an error.  I'll
verify and submit a bug report.]

You could make it work by opennig in 'rb+' mode, and doing a seek.
But a much cleaner approach is opening the file again, now for writing only:

f = file('project_release2.a', 'wb')
a.tofile(f)
f.close()

[And since Python 2.6, you can simply write:

with file('project_release2.a', 'wb') as f:
    a.tofile(f)

which guarantees closing even if an exception happens.
Works for reading too, of course.]

On Sun, Dec 27, 2009 at 15:41, Yitzhak Wiener <Yitzhak.Wiener at dspg.com>wrote:

>  Hi Dear People,
>
>
>
> As really beginner in Python, I tried to write a simple script that opens a
> binary file and replace all appearance of some data with another data.
>
> It doesn’t show me any error message, but file is not modified. Can you
> help to understand why?
>
>
>
> My script is as follows:
>
> from array import array
>
> a = array('H')
>
> f =  file('project_release.a')
>
> a.fromfile( f,100 )
>
>
>
> # update the content
>
> for i in a:
>
>    if i == 0xFFFF:
>
>        a[ a.index(i) ] = 0x7777
>
>
>
>
>
> #update to new file
>
> a.tofile(f)
>
>
>
>
>
> Thanks,
>
> Yitzhak
>
>
>
> ______________________________________________________________________
> DSP Group, Inc. automatically scans all emails and attachments using
> MessageLabs Email Security System.
> _____________________________________________________________________
>
> _______________________________________________
> Python-il mailing list
> Python-il at hamakor.org.il
> http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
>
>


-- 
Beni Cherniavsky-Paskin <cben at users.sf.net>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://hamakor.org.il/pipermail/python-il/attachments/20091227/6a829fe4/attachment-0001.htm 


More information about the Python-il mailing list