[Tutor] binary data struct module
Kent Johnson
kent37 at tds.net
Tue Sep 4 13:46:20 CEST 2007
John wrote:
> f2=file(infile,'rb')
>
> Dfmt=['3i','13s','7i','2f','2i','2f','2i','i'] #format for binary
> reading first bits
>
> if f2:
> print infile + ' has been opened'
> #for ft in Dfmt:
> # print ft
> a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt)
> for ln in a: print ln
however, how can I now assign variables based on the 'generator object'
> a? What exactly is this?
a is a generator which is an iterable object. Access to its values is
through the iterator protocol such as the for loop you use.
> My question is, how can I now work with 'a' so that i can use the values?
Use a list comprehension instead of a generator expression:
a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt]
This creates a list instead of a generator object.
Kent
More information about the Tutor
mailing list