[英]Python search and replace in binary file
我試圖在這個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'
后
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
怎么做到最好?
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名稱
您必須使用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
對象中,replace的參數必須都是 bytes
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.