[Tutor] binary file query

Alan Gauld alan.gauld at btinternet.com
Wed Nov 16 13:06:01 CET 2011


On 14/11/11 05:34, Shirkhedkar, Dhanashri wrote:
> If we are opening a binary file in python then do we have to use “Import
> struct” and do “struct.unpack” to work on the data from that binary file?

That depends but in general the answer is no.
But it all depends on what is in the file. If it is a known format (like 
Pickle say) there may well be a higher level module that will interopret 
the file for you. But fundamentally, opening a file in binary mode means 
you are reading the raw bytes from the file and the interpretation of 
those bytes is entirely your responsibility.

> Will we be able to process the file as text file without using struct?

Only if the bytes represent text. You can certainly treat the bytes as 
if they were text and interesting things may happen. Whether the text 
interpretation bears any resemblance to the original intent of the files 
author is another matter all together.

The key thing in dealing with binary files is that you must know what 
the bytes you are reading represent (or be willing to reverse engineer 
it!). If an existing interpreter (eg pickle, PIL, gzip etc) exists that 
will make life easier. If not you can either read the bytes into a list 
and process them manually. Or, if you know what they represent, you can 
use struct to convert them into appropriate Python data objects.

The choice is yours and depends on many factors.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list