How to read file headers in Python similar to C?

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

In C (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 the header data such as ptr-> type, ptr-> magic, etc.

How to achieve a similar effect in Python? Since Python variables are typeless, what is the best way to access file header data?

I need to use header data to make some decisions.

Thanks at Advance.

+5
source share
2 answers

- python struct, docs .
, - , - construct, .

+6

struct Python. , , .

- , struct.unpack().

+3

All Articles