Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Read string from binary file

Tags:

python

I need to read up to the point of a certain string in a binary file, and then act on the bytes that follow. The string is 'colr' (this is a JPEG 2000 file) and here is what I have so far:

from collections import deque

f = open('my.jp2', 'rb')
bytes =  deque([], 4)
while ''.join(map(chr, bytes)) != 'colr':
    bytes.appendleft(ord(f.read(1)))

if this works:

bytes =  deque([0x63, 0x6F, 0x6C, 0x72], 4)
print ''.join(map(chr, bytes))

(returns 'colr'), I'm not sure why the test in my loop never evaluates to True. I wind up spinning - just hanging - I don't even get an exit when I've read through the whole file.

like image 925
JStroop Avatar asked Feb 02 '26 01:02

JStroop


1 Answers

Change your bytes.appendleft() to bytes.append() and then it will work -- it does for me.

like image 130
martineau Avatar answered Feb 04 '26 15:02

martineau