Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #67672

Re: find and replace string in binary file

From Peter Otten <__peter__@web.de>
Subject Re: find and replace string in binary file
Date 2014-03-04 14:18 +0100
Organization None
References <01951a7d-2ab3-4203-a9c5-2f79017a980d@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.7709.1393939155.18130.python-list@python.org> (permalink)

Show all headers | View raw


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. Consider

#python3
ENCODING = "iso-8859-1"
with open(source, encoding=ENCODING) as infile:
    data = infile.read()
with open(dest, "w", encoding=ENCODING) as outfile:
    outfile.write(data.replace("nötig", "möglich"))

If the file is indeed iso-8859-1 this will replace occurrences of the bytes

b'n\xf6tig' with b'm\xf6glich'

But if you were guessing wrong and the file is utf-8 it may contain the 
bytes b'n\xc3\xb6tig' instead which are incorrectly interpreted by your 
script as 'nötig' and thus left as is.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

find and replace string in binary file loial <jldunn2000@gmail.com> - 2014-03-04 04:27 -0800
  Re: find and replace string in binary file MRAB <python@mrabarnett.plus.com> - 2014-03-04 13:08 +0000
  Re: find and replace string in binary file Peter Otten <__peter__@web.de> - 2014-03-04 14:18 +0100
  Re: find and replace string in binary file Chris Angelico <rosuav@gmail.com> - 2014-03-05 09:44 +1100
  Re: find and replace string in binary file emile <emile@fenx.com> - 2014-03-04 16:13 -0800
    Re: find and replace string in binary file loial <jldunn2000@gmail.com> - 2014-03-05 01:59 -0800
      Re: find and replace string in binary file Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-03-05 12:42 +0000
      Re: find and replace string in binary file Emile van Sebille <emile@fenx.com> - 2014-03-05 09:46 -0800
  Re:find and replace string in binary file Dave Angel <davea@davea.name> - 2014-03-05 07:06 -0500

csiph-web