Python – Unable to read hexadecimal 0A correctly

Unable to read hexadecimal 0A correctly… here is a solution to the problem.

Unable to read hexadecimal 0A correctly

I’m trying to read 2 bytes from a hexadecimal file at a time.

f = open(filename, "rb+")

seekv = 0
x = 16
while x > 0:
     x = x-1
     f.seek(seekv)
     seekv = seekv + 1
     Nextb = binascii.hexlify(f.readline(2))
     print Nextb

The problem is that if those 2 bytes are 0a0a, it will only read one byte 0a. I suspect this has something to do with 0x0A being new lines in ASCII, but this shouldn’t happen.

Solution

You are using f.readline(2) instead of f.read(2).

The readline will use one of the 0a as a marker to know where the new line begins. If you switch to f.read(2), you should see both.

You really shouldn’t use a readline for binary data.

Related Problems and Solutions