stripping the first byte from a binary file

rvr rvanroode at gmail.com
Wed Jul 11 06:02:48 EDT 2007


On Jul 11, 1:28 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Wed, 11 Jul 2007 01:06:04 +0000, rvr wrote:
> > Is there a way to edit the file in place? The best I seem to be able to
> > do is to use your second solution to read the file into the string, then
> > re-open the file for writing and put the whole thing back (minus the
> > first byte). Thanks.
>
> I don't believe that any of the popular operating systems in common use
> (Windows, Linux, Mac, *BSD) have any such functionality.
>
> For safety, you are best off copying the file (minus the first byte) to a
> temporary file, then renaming the copy over the original. That way if
> your process dies midway through copying the file, you don't lose data.
>
> Renaming the file is atomic under Linux and (probably) Mac, so it is as
> safe as possible. Even under Windows, which isn't atomic, it has a
> smaller margin for disaster than over-writing the file in place.

Thanks for your response. While searching for solution, I found this:

   http://mail.python.org/pipermail/python-list/2001-December/116519.html

Quoting from it:

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

Can I use the seek() and write() methods in a similar way to remove
the first byte? For whatever reason I can't seem to make it work
myself. Thanks again.

~rvr




More information about the Python-list mailing list