Struct.Pack and Binary files

PurpleServerMonkey PurpleServerMonkey at gmail.com
Sun Jan 27 20:23:33 EST 2008


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)
            clientSocket.sendto(outdata, DestAddress)

I've reused the basic structure below for a binary file, the issue I'm
having is working out the correct format string. At first I thought a
float or double would have been the one to use but the interpreter
complains about invalid types being passed.

fileHandle = open("test.zip", "rb")

while loop:
            fileBuffer = fileHandle.read(512)
            format = "!hh%dd" % len(fileBuffer)
            outdata = struct.pack(format,  *fileBuffer)
            clientSocket.sendto(outdata, DestAddress)

If someone could shed some light on the problem it would be
appreciated, I'm clearly missing something fairly obvious.

Thanks in advance.



More information about the Python-list mailing list