二进制文件中的Python搜索和替换

二进制文件中的Python搜索和替换,python,replace,binary-data,Python,Replace,Binary Data,我正在尝试搜索并替换此pdf表单文件(header.fdf,我假定此文件被视为二进制文件)中的一些文本(例如“Smith,John”): 出现以下错误: Traceback (most recent call last): File "/home/aj/Inkscape/Med/GAD/gad.py", line 56, in <module> s=s.replace(b'PatientName',name) TypeError: expected an object w

我正在尝试搜索并替换此pdf表单文件(header.fdf,我假定此文件被视为二进制文件)中的一些文本(例如“Smith,John”):

出现以下错误:

Traceback (most recent call last):
  File "/home/aj/Inkscape/Med/GAD/gad.py", line 56, in <module>
    s=s.replace(b'PatientName',name)
TypeError: expected an object with the buffer interface
回溯(最近一次呼叫最后一次):
文件“/home/aj/Inkscape/Med/GAD/GAD.py”,第56行,在
s=s.replace(b'PatientName',name)
TypeError:应为具有缓冲区接口的对象
如何最好地做到这一点

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


可能是后者,因为我认为您无论如何都不能在这种替换类型中使用unicode名称

您必须使用Python 3.X。您在示例中没有定义“name”,但这就是问题所在。很可能您将其定义为Unicode字符串:

name = 'blah'
它也需要是字节对象:

name = b'blah'
这项工作:

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'

bytes
对象中,要替换的参数必须都是
bytes
对象。

b'PatientName'中
b
应该是什么意思?丢掉它!;-)@Nas Banov,
b
表示Python2.6+中的字节,与原始srtings的
r
或Python2.6+中的
u
非常相似unicode@gnibbler:实际上,在Python3.x之前的版本中,我找不到提到b''。难怪我从来没有听说过这种新式的东西:)。然而,这个错误也是来自Python3。谢谢您的回复。它在我的linux系统上运行良好。但是,当我在windows系统上尝试它时,它并不是这样的:f=open(“header.fdf”,“rb”)s=f.read()print(s)或print(str(s)),结果是:-------------------------------------%fdf-1.2%1.0 obj
name = 'blah'
name = b'blah'
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'