I am trying to search and replace some of the text (eg \'Smith, John\') in this pdf form file (header.fdf, I presumed this is treated as binary file):
\'%FDF-1.2
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 win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('file.txt','rb')
>>> s = f.read()
>>> f.close()
>>> s
b'Test File\r\n'
>>> name = b'Replacement'
>>> s=s.replace(b'File',name)
>>> s
b'Test Replacement\r\n'
In a bytes
object, the arguments to replace must both be bytes
objects.
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