Search code examples
pythonbinaryfiles

remove 4 bytes after seek to specific location in binary file - python


I am reading a Hexadecimal binary file. I need to remove bytes after seek command to specific location. Below code is reading binary file. But i don't know how to remove 4 bytes in middle of file.

 import os
 import struct

 with open("esears36_short.dat", "rb") as f:
    data = f.read(2)
    number = struct.unpack(">h", data)[0]
    f.seek(number, 1)
    #need to code to remove 4 bytes

I need to execute this code in loop until EOF. Remove 4 bytes after every n bytes specfied in number field.

Value of number field in this case : 28045

Please help!


Solution

  • To remove 4 bytes you have to copy the remaining file forward 4 bytes and that can be messy as you are reading and writing buffers in the same file. Its easier to write a new file and rename. In that case, you just seek ahead 4 bytes as needed.

    import os
    import struct
    
    with open("esears36_short.dat", "rb") as f, open("esars32_short.dat.tmp", 'wb') as f_out:
        data = f.read(2)
        number = struct.unpack(">h", data)[0]
        f.seek(2, 1)
        while True:
            buf = f.read(number)
            if not buf:
                break
            f_out.write(buf)
            f.seek(4, 1) # 4 bytes forward
    os.remove("esears36_short.dat")
    os.rename("esars32_short.dat.tmp", "esears36_short.dat")
    

    Although you are writing a new file you are doing less actual copying.