How to overwrite some bytes in the middle of a file with Python?

前端 未结 3 1387

I\'d like to be able to overwrite some bytes at a given offset in a file using Python.

My attempts have failed miserably and resulted in:

  • overwriting t
相关标签:
3条回答
  • 2020-12-05 18:58

    Try this:

    fh = open("filename.ext", "r+b")
    fh.seek(offset)
    fh.write(bytes)
    fh.close()
    
    0 讨论(0)
  • 2020-12-05 19:07

    Very inefficient, but I don't know any other way right now, that doesn't overwrite the bytes in the middle (as Ben Blanks one does):

    a=file('/tmp/test123','r+')
    s=a.read()
    a.seek(0)
    a.write(s[:3]+'xxx'+s[3:])
    a.close()
    

    will write 'xxx' at offset 3: 123456789 --> 123xxx456789

    0 讨论(0)
  • 2020-12-05 19:11

    According to this python page you can type file.seek to seek to a particualar offset. You can then write whatever you want.

    To avoid truncating the file, you can open it with "a+" then seek to the right offset.

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