views:

180

answers:

2

I am new to Python. I am a C programmer by profession. I have file, whose header has some specific data, that I need to extract. For example, Byte 0-5 has a magic, Byte 6-8 has offset etc.

In C (An Example) :

struct {  
   int32_t payload_offset,  
   int32_t len,  
   char *magic,  
   int32_t type  
   int32_t header_size  
} file_hdr;  

Then in my function, I do the following:

file_hdr *hdr;
ptr = &hdr;
fd = open(path_to_file, "r");
num_read =  read(fd, ptr, bytes). 

Then I can access header data like this ptr->type, ptr->magic etc.

How do I achieve similar effect in Python? Since Python variables do not have types, what is the best way to access file header data?

I need to use the header data for making some decisions.

Thanks in Advance.

+6  A: 

One way is to use the python struct module, docs are here.
Another option, if you need something more powerful, is to use the awesome construct library that can do the above and much more.

abyx
+2  A: 

This is typically done using the struct module in Python. It allows you to extract values from packed binary representations, driven by format-specification strings that you provide.

You would load the data in using binary I/O into a string, then unpack it using struct.unpack().

unwind