2

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..

0

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

It's worth noting that this still may raise the same exception if file_read is a file containing an odd number of bytes. However, that would be a problem with the input and not a problem with the code.
1

Most probably file_read is empty or gets empty after reading line (as @MisterMiyagi noted, reading binary files line by line doesn't seem to be a good idea). So file_read.read reads nothing or just one byte. You can verify it by printing len(bytes).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.