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.
-
Did you have a look at stackoverflow.com/questions/6822725/… ?Dr. Jan-Philip Gehrcke– Dr. Jan-Philip Gehrcke2012年09月12日 19:41:17 +00:00Commented Sep 12, 2012 at 19:41
-
@Jan-Philip - thanks! I should probably look at adapting one of those. First and foremost, though, this answer stackoverflow.com/a/6822761/714478 made me realize that I was just appending to the wrong side of the deque, and my method above, with that correction, works just fine!JStroop– JStroop2012年09月12日 20:47:03 +00:00Commented Sep 12, 2012 at 20:47
2 Answers 2
Change your bytes.appendleft() to bytes.append() and then it will work -- it does for me.
Comments
with open("my.jpg","rb") as f:
print f.read().split("colr",1)
if you dont want to read it all at once ... then
def preprocess(line):
print "Do Something with this line"
def postprocess(line):
print "Do something else with this line"
currentproc = preprocess
with open("my.jpg","rb") as f:
for line in f:
if "colr" in line:
left,right = line.split("colr")
preprocess(left)
postprocess(right)
currentproc= postprocess
else:
currentproc(line)
its line by line rather than byte by byte ... but meh ... I have a hard time thinking that you dont have enough ram to hold the whole jpg in memory... python is not really an awesome language to minimize memory or time footprints but it is awesome for functional requirements :)
8 Comments
f byte by byte after the split()f.read() reads the entire file, so just store this data in a variable, then split() as suggested by Joran and, after that, continue processing the data.