【问题标题】:Python search and replace in binary filePython在二进制文件中搜索和替换
【发布时间】:2011-03-10 21:48:59
【问题描述】:

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

'%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'

之后

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

出现以下错误:

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

如何最好地做到这一点?

【问题讨论】:

  • bb'PatientName' 中应该是什么意思?失去它! ;-)
  • @Nas Banov, b 表示 Python2.6+ 中的字节,与 r 用于原始 srtings 或 u 用于 unicode 非常相似
  • @gnibbler:实际上我在 Python 3.x 之前的任何内容中都找不到提及 b''。难怪我从来没有听说过这个新奇的东西:)。然而,错误也来自 Python 3。

标签: python replace binary-data


【解决方案1】:
f=open("header.fdf","rb")
s=str(f.read())
f.close()
s=s.replace(b'PatientName',name)

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

可能是后者,因为我认为无论如何您都无法将 unicode 名称用于这种类型的替换

【讨论】:

  • 感谢您的回复。它在我的 linux 系统上运行良好。但是,当我在 Windows 系统上尝试时却没有: f=open("header.fdf","rb") s=f.read() print(s) # or print(str(s)) # This结果: ------------- %FDF-1.2 %âãÏÓ 1 0 obj
【解决方案2】:

您必须使用 Python 3.X。您没有在示例中定义“名称”,但这就是问题所在。很可能您将其定义为 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 对象。

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 2019-04-21
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多