find and replace string in binary file
loial
jldunn2000 at gmail.com
Wed Mar 5 04:59:00 EST 2014
Thanks Emile.
Unfortunately I have to use python 2.6 for this
On Wednesday, 5 March 2014 00:13:00 UTC, emile wrote:
> On 03/04/2014 02:44 PM, Chris Angelico wrote:
>
> > On Wed, Mar 5, 2014 at 12:18 AM, Peter Otten <__peter__ at web.de> wrote:
>
> >> loial wrote:
>
> >>
>
> >>> How do I read a binary file, find/identify a character string and replace
>
> >>> it with another character string and write out to another file?
>
> >>>
>
> >>> Its the finding of the string in a binary file that I am not clear on.
>
> >>
>
> >> That's not possible. You have to convert either binary to string or string
>
> >> to binary before you can replace. Whatever you choose, you have to know the
>
> >> encoding of the file.
>
> >
>
> > If it's actually a binary file (as in, an executable, or an image, or
>
> > something), then the *file* won't have an encoding, so you'll need to
>
> > know the encoding of the particular string you want and encode your
>
> > string to bytes.
>
>
>
>
>
> On 2.7 it's as easy as it sounds without having to think much about
>
> encodings and such. I find it mostly just works.
>
>
>
> emile at paj39:~$ which python
>
> /usr/bin/python
>
> emile at paj39:~$ python
>
> Python 2.7.3 (default, Sep 26 2013, 16:38:10)
>
> [GCC 4.7.2] on linux2
>
> Type "help", "copyright", "credits" or "license" for more information.
>
> >>> image = open('/usr/bin/python','rb').read()
>
> >>> image.find("""Type "help", "copyright", "credits" """)
>
> 1491592
>
> >>> image = image[:1491592]+"Echo"+image[1491592+4:]
>
> >>> open('/home/emile/pyecho','wb').write(image)
>
> >>>
>
> emile at paj39:~$ chmod a+x /home/emile/pyecho
>
> emile at paj39:~$ /home/emile/pyecho
>
> Python 2.7.3 (default, Sep 26 2013, 16:38:10)
>
> [GCC 4.7.2] on linux2
>
> Echo "help", "copyright", "credits" or "license" for more information.
>
>
>
> YMMV,
>
>
>
> Emile
More information about the Python-list
mailing list