Python search and replace in binary file

前端 未结 2 1465
暗喜
暗喜 2021-02-12 18:53

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         


        
相关标签:
2条回答
  • 2021-02-12 19:29
    f=open("header.fdf","rb")
    s=str(f.read())
    f.close()
    s=s.replace(b'PatientName',name)
    

    or

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

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

    0 讨论(0)
  • 2021-02-12 19:42

    You must be using Python 3.X. You didn't define 'name' in your example, but it is the problem. Likely you defined it as a Unicode string:

    name = 'blah'
    

    It needs to be a bytes object too:

    name = b'blah'
    

    This works:

    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'
    

    In a bytes object, the arguments to replace must both be bytes objects.

    0 讨论(0)
提交回复
热议问题