Python search and replace in binary file

前端 未结 2 1659
旧时难觅i
旧时难觅i 2021-02-12 19:19

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:36

    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.

提交回复
热议问题