Unpacking byte strings from a file of unknown size

Steven Clark steven.p.clark at gmail.com
Mon Oct 27 17:03:37 EDT 2008


On Mon, Oct 27, 2008 at 4:29 PM, Mark <mseagoe at gmail.com> wrote:
> Hi;
>
> I'm trying to use the struct.unpack to extract an int, int, char
> struct info from a file.  I'm more accustomed to the file.readlines
> which works well in a 'for' construct (ending loop after reaching
> EOF).
>
> # This does OK at fetching one 10-byte string at a time:
> # (4, 4, 2 ascii chars representing hex)
> info1, info2, info3 = struct.unpack('<IIH', myfile.read(10))
>
> # Now to do the entire file, putting into a loop just gives error:
> # TypeError: 'int' object is not iterable
> for info1, info2, info3 in struct.unpack('<IIH', myfile.read(10)):
>
> In trying to shoehorn this into a 'for' loop I've been unsuccessful.
> I also tried other variations that also didn't work but no point
> wasting space.  Using Python 2.5, WinXP
>
> Thx,
> Mark
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I usually do something like:
s = myfile.read(10)
while len(s) == 10:
    info1, info2, info3 = struct.unpack('<IIH', s)
    s = myfile.read(10)
#might want to check that len(s) == 0 here



More information about the Python-list mailing list