Python search and replace in binary file Python search and replace in binary file python python

Python search and replace in binary file


f=open("header.fdf","rb")s=str(f.read())f.close()s=s.replace(b'PatientName',name)

or

f=open("header.fdf","rb")s=f.read()f.close()s=s.replace(b'PatientName',bytes(name))

probably the latter, as I don't think you are going to be able to use unicode names with this type of substitution anyway


You must be using Python 3.X. You didn't define 'name' in your example, but it is the problem. Likely you defined it as a Unicode string:

name = 'blah'

It needs to be a bytes object too:

name = b'blah'

This works:

Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> f = open('file.txt','rb')>>> s = f.read()>>> f.close()>>> sb'Test File\r\n'>>> name = b'Replacement'>>> s=s.replace(b'File',name)>>> sb'Test Replacement\r\n'

In a bytes object, the arguments to replace must both be bytes objects.