Python搜索并替换为二进制文件 [英] Python search and replace in binary file

查看:178
本文介绍了Python搜索并替换为二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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\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

如何最好地做到这一点?

How best to do this?

推荐答案

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名称

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

这篇关于Python搜索并替换为二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆