stripping the first byte from a binary file

Alex Popescu the.mindstorm.mailinglist at gmail.com
Wed Jul 11 07:30:16 EDT 2007


On Jul 11, 1:25 pm, Stefan Behnel <stefan.behnel-n05... at web.de> wrote:
> rvr wrote:
> > 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.
>
> Funny. I just happened to read ESR's "how to ask questions the smart way" and
> your posts match quite a few of the examples. :)
>
> No, you can't. Steven's solution is what I'd go for.
>
> Stefan

Forgive my newbie ignorance, but I am wondering why the other method
would not work? I mean it may not be very safe,
but I guess it may perform a lot better, than having to read the whole
file just to cut out the first byte.

TIA,

./alex
--
.w( the_mindstorm )p.






More information about the Python-list mailing list