[Tutor] binary file query

Alan Gauld alan.gauld at btinternet.com
Fri Nov 18 00:39:11 CET 2011

On 17/11/11 14:55, Prasad, Ramit wrote:

> It means that no need to use the 'Struct' module for binary file read,
> right?

Its not necessary but if the data does not already have a file handling 
module then the struct module is a very convenient way of accessing the 

> It really depends on your file. The struct module says, "This module
> performs conversions between Python values and C structs represented
> as Python strings." If your file is not a C-struct data then no need
> to use the struct module.

No *need* but, often convenient, regardless of whether the data was 
written by a C struct or not.(*) It is a way to interpret binary data in 
terms of fundamental data types such as ints, floats, strings etc.

Trying to convert raw bytes representing floats into a floating point 
number without using struct would be an interesting exercise. Using 
struct it's trivial.

Struct works with any kind of basic binary data provided you know what 
the byte sequence represents. Where it breaks down is when it represents 
more complex concepts like references to objects and even graphical 
bitmaps etc. That's where dedicated file handling modules
come into play.

(*)The struct docs acknowledge this with the following comment:
"To handle platform-independent data formats or omit implicit pad bytes, 
use standard size and alignment instead of native size and alignment: 
see Byte Order, Size, and Alignment for details."

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list