Search code examples
pythonpython-3.6binaryfiles

Reading binary files using python3


I am trying to read a 16-bit binary file in python3 and I'm getting the following error

out = struct.unpack("h", bytes)
error: unpack requires a buffer of 2 bytes

import struct
for line in file_read:
    bytes = file_read.read(2)
    out = struct.unpack("h", bytes)
    file_write.write(str(out))

any suggestion on where i might be going wrong will be much appreciated..


Solution

  • You are traversing your file both by line and by byte-characters.

    for line in file_read:  # read by line
        bytes = file_read.read(2)  # read by character
    

    The first seeks newlines (b'\n' aka b'\x0A') and may consume an arbitrary number of bytes. This means your reading of byte pairs is likely offset by 1, and possibly at the end of the file.

    Read your file only by character pairs. You can use the two-argument iter to conveniently do this in a for loop:

    for pair in iter(lambda: file_read.read(2), b''):
        out = struct.unpack("h", pair)
        file_write.write(str(out))
    

    In Python 3.8, you can use an assignment expression as well:

    while pair := file_read.read(2):
        out = struct.unpack("h", pair)
        file_write.write(str(out))