python - 如何在类似于 C 的 Python 中读取文件头?

标签 python file-io header

我是 Python 新手。我的职业是 C 程序员。我有一个文件,其标题有一些我需要提取的特定数据。例如0-5字节有magic,6-8字节有offset等。

在 C 中(示例):

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

然后在我的函数中,我执行以下操作:

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

然后我可以访问像这样的 ptr->type、ptr->magic 等头数据。

如何在 Python 中实现类似的效果?由于 Python 变量没有类型,访问文件头数据的最佳方式是什么?

我需要使用标题数据来做出一些决定。

提前致谢。

最佳答案

一种方法是使用 python struct 模块,文档是 here .
如果您需要更强大的功能,另一种选择是使用很棒的 construct可以执行上述以及更多操作的库。

关于python - 如何在类似于 C 的 Python 中读取文件头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2085464/

相关文章:

c++ - “std_lib_facilities.h”显示错误

jQuery JSON 请求得到 '200 OK' 答案,但没有内容

c++ - 从文件中读取返回一个我没想到的结果,试图理解为什么

javascript - 如何在 Prestashop - 1.6 的顶部标题中添加广告脚本?

python - 在 PyQt5 中的图像顶部绘制跟踪鼠标

python - 比较列表元素与多个列表元素

php - 假文件句柄创建

C++ undefined symbol

python - Python 中 for 循环和打印列表的顺序是什么?

python - 无法理解 lambda 函数