Is Python suitable for some binary file editing?

Tim Hammerquist tim at vegeta.ath.cx
Wed Dec 5 04:38:57 EST 2001


Richard Jones <richard at bizarsoftware.com.au> graced us by uttering:
[ snip ]
> A very simple example of replacing two bytes in a file, 100 bytes in:
> 
> [richard at ike /tmp]% python
> Python 2.1.1 (#1, Aug 30 2001, 17:36:05) 
> [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.61mdk)] on linux-i386
> Type "copyright", "credits" or "license" for more information.
>>>> f = open('test_input', 'rb')
>>>> o = open('test_output', 'wb')
>>>> o.write(f.read(100))
>>>> o.write(chr(123))
>>>> o.write(chr(0x80))
>>>> f.read(2)
> 'ri'
>>>> o.write(f.read())

I'd have preferred:

Replace 2 bytes in place beginning at offset 100 (101st byte):

    f = open('text_input', 'r+b')
    f.seek(100)
    f.write(chr(123) + chr(0x80))
    f.seek(0,2)
    f.close()

Tim Hammerquist
-- 
scanf() is evil.



More information about the Python-list mailing list