Struct.Pack and Binary files

PurpleServerMonkey PurpleServerMonkey at gmail.com
Mon Jan 28 10:44:38 CET 2008


On Jan 28, 1:48 pm, Grant Edwards <gra... at visi.com> wrote:
> On 2008-01-28, PurpleServerMonkey <PurpleServerMon... at gmail.com> wrote:
>
> > Having trouble working out an appropriate format string for packing a
> > binary file.
>
> > The below is something I use for ASCII files but now I need something
> > equivalent for working with binary files i.e jpg, zips etc.
>
> > fileHandle = open("test.txt")
>
> > while loop:
> >             fileBuffer = fileHandle.read(512)
> >             format = "!hh%dc" % len(fileBuffer)
> >             outdata = struct.pack(format,  *fileBuffer)
>
> Assuming fileBuffer has 512 bytes in it, your format string is
> going to be "!hh512c".  When struct.pack sees that, it expects
> 514 values to pack.  You're only passing it 512.  What data do
> you want to be packed into the two "h" fields?
>
> You're also wasting a lot of CPU time unpacking and then
> repacking the 512 bytes in filebufffer.  I suspect what you
> want is:
>
>    val1 = ???
>    val2 = ???
>    outdata = format.struct("!hh", val1, val2) + fileBuffer
>
> I don't know what val1 and val2 are supposed to be, since the
> values that are to be packed as the two "h" fields seems to be
> missing from your example code.
>
> --
> Grant

Thanks Grant,

Yeah I left out the two 'h' values by mistake but your suggestion
worked out really well.



More information about the Python-list mailing list