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

ajo*_*ajo 15 python replace binary-data

我试图在这个pdf格式文件中搜索并替换一些文本(例如'Smith,John')(header.fdf,我认为这被视为二进制文件):

'%FDF-1.2\n%\xe2\xe3\xcf\xd3\n1 0 obj\n<</FDF<</Fields[<</V(M)/T(PatientSexLabel)>><</V(24-09-1956  53)/T(PatientDateOfBirth)>><</V(Fisher)/T(PatientLastNameLabel)>><</V(CNSL)/T(PatientConsultant)>><</V(28-01-2010 18:13)/T(PatientAdmission)>><</V(134 Field Street\\rBlackburn BB1 1BB)/T(PatientAddressLabel)>><</V(Smith, John)/T(PatientName)>><</V(24-09-1956)/T(PatientDobLabel)>><</V(0123456)/T(PatientRxr)>><</V(01234567891011)/T(PatientNhsLabel)>><</V(John)/T(PatientFirstNameLabel)>><</V(0123456)/T(PatientRxrLabel)>>]>>>>\nendobj\ntrailer\n<</Root 1 0 R>>\n%%EOF\n'
Run Code Online (Sandbox Code Playgroud)

f=open("header.fdf","rb")
s=f.read()
f.close()
s=s.replace(b'PatientName',name)
Run Code Online (Sandbox Code Playgroud)

发生以下错误:

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
Run Code Online (Sandbox Code Playgroud)

怎么做到最好?

Joh*_*ooy 18

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

要么

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

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

  • 感谢您的答复。它在我的 Linux 系统上运行良好。然而,当我在 Windows 系统上尝试时却没有: f=open("header.fdf","rb") s=f.read() print(s) # 或 print(str(s)) # This结果: ------------------------- %FDF-1.2 %âãÏÓ 1 0 obj &lt;&lt; /FDF &lt;&lt; /Fields [ &lt;&lt; /V (þÿ --------------------- 我猜编码是错误的,但不知道从这里去哪里...... (3认同)

Mar*_*nen 6

您必须使用Python 3.X. 您没有在示例中定义"名称",但这是问题所在.您可能将其定义为Unicode字符串:

name = 'blah'
Run Code Online (Sandbox Code Playgroud)

它也需要是一个字节对象:

name = b'blah'
Run Code Online (Sandbox Code Playgroud)

这有效:

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'
Run Code Online (Sandbox Code Playgroud)

在一个bytes对象,参数更换必须bytes对象.