Is Python suitable for some binary file editing?

Richard Jones richard at bizarsoftware.com.au
Tue Dec 4 22:51:23 EST 2001


On Wednesday 05 December 2001 13:54, Tim Hammerquist wrote:
> David Rollo <drollo at cns.net.au> graced us by uttering:
> > I am considering as a beginning Python project an iterative task
> > involving conversion of a set of image files to an alternative format.
> > The file conversion is simply making the same change to a handful of
> > characters at a particular offset, and saving under a new filename. It
> > would be repeated several thousand times, looping through a hierarchical
> > directory structure in Windows, editing and renaming as it went.
> >
> > Does this sound like the sort of task that Python is suited to? I had
> > planned to do it in Java, but wondered if this might be the time to cut
> > teeth in Python.
>
> This not only sounds like a job better done in Python, it sounds like
> _fun_ to do in Python.
>
> Remember to use binary mode on Win32!

For this application, the programer would be advised to use binary mode 
regardless, and certainly not make the binaryness of the file open dependant 
on platform!

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())


    Richard




More information about the Python-list mailing list