On Tue, Nov 06, 2007 at 07:44:53PM +0000, Jan T. Kim wrote:
tagNum = tlvFile.read(3) while tagNum: # do stuff with tagNum tagNum = tlvFile.read(3)
would probably work. Not sure how you are intending to handle your variable record length stuff in a while loop though.
Yes, I just don't feel those two tlvFile.read(3) calls are very elegant somehow.
If elegance is the issue, objects are perhaps a solution; you can write yourself a little class that allows you to iterate over the file using a for loop:
class FileSequence(object) :
def __init__(self, f) : self.f = f
def __iter__(self) : return self
def next(self) : s = self.f.read(3) if s == '' : raise StopIteration return s
fs = FileSequence(file(sys.argv[1], 'r')) for w in fs : print w
Obviously, the next method can read and return chunks of variable length and instance variables can be used for any state required to work out chunk lengths or perhaps to buffer stuff... so this might even be useful in addition to being elegant... in fact, pretty neat lexical scanners can be written this way.
Now that's the sort of solution I was after, thank you! :-)