开发者

How to read file headers in Python similar to C?

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? Sin开发者_如何学运维ce 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.


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.


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜